How does inheritance in Java work?

前端 未结 6 1927
迷失自我
迷失自我 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

    super is a keyword allowing you to call the method implementation defined in the superclass. It is not a field of your sub-class.

    If it is not, where are overrided method hold?

    I'm not quite sure what you mean by this, but:

    • the method which prints "Super" is held in the class definition of the superclass
    • the method which prints "Sub" is held in the class definition of the subclass.

    Since Sub extends Super, the definition of the Sub class includes a reference to the definition of the Super class.

    Answering updated questions:

    When we are calling method with super, you say, we are acessing parent's method. But how can we call this method without parent's object?

    A method is just a block of code, just a sequence of bytecode instructions that we need to execute. When you invoke a method, the JVM's task is to determine, from the method name and parameters you give, where to find this block of code. Normally, as others have said, it will first look in the class definition of the class of the object on which the method was invoked. When you use super, you are telling the JVM not to look here, and instead look in the parent class definition.

    So you don't need separate instances of Super and Sub, because a Sub is a Super (new Sub() instanceof Super is true), and because the JVM knows that the super keyword means that it should look for the code composing a method in the class definition of Super.

    Is super same as this? this is a reference to concrete object, as you know.

    No, they're not the same. this is a reference to the current object, whereas super is not a reference to an object, instead it is a keyword which affects where the JVM will look for the code defining a method which is being invoked.

提交回复
热议问题