How does inheritance in Java work?

前端 未结 6 1922
迷失自我
迷失自我 2020-12-09 21:23

We have next classes:

class Super {
    void foo() {
        System.out.println(\"Super\");
    }
}

class Sub extends Super {
    void foo() {
        super         


        
6条回答
  •  一整个雨季
    2020-12-09 22:05

    Okay. Let's go, line by line through your code.

    Your first statement, in your 'foo' method is

    super.foo();
    

    Well that's an explicit call to the superclass foo method. Which is:

     void foo() {
        System.out.println("Super");
    }
    

    So "Super" is outputted to the console, becuase you've explicitly called this method with the super keyword. super refers to the class' superclass, in the same way that this refers to the current class.

    Next is the rest of the foo method in the subclass:

     void foo() {
        super.foo();
        System.out.println("Sub");
    }
    

    Well after super.foo() is called, it's time to move to the next statement, which outputs "Sub".


    The reason why your program moves to the subclass' method first, instead of the superclass, is because of a principle called Polymorphism. That is, a subclass takes a method from the superclass, and alters it's behavior.

    Abstract Classes

    You can't create instances of Abstract classes, no, but with the super keyword, you can access the functionality of the superclass nonetheless.

    In context of the Java Virtual Machine

    So what happens, when you make a method call, is the Java Virtual Machine will look for the method in the local class, if it is an instance method. If it can not find it, it will move to the superclass. When you use the principle of Polymorphism, the JVM finds the method with the correct signature in the subclass, and stops looking. This is how inheritance and Polymorphism works in simple terms, in the context of Java.

    When you override a method, you add a method with the same method signature (the name, number and type of a method's fields) to the subclass definition. This is how the JVM finds it, and this is where the overridden method is stored.

提交回复
热议问题