简体   繁体   中英

What happen when you call an override method using super and this keyword?

public class Superclass {



    void method0(){
        System.out.println("superclass");
    }
}


public class Subclass extends Superclass{

    void method0(){
        System.out.println("subclass");
    }

    void method1(){
        super.method0();
    }

    void method2(){
        this.method0();
    }
}


public class RunClass {

    public static void main(String[] args){
        new Subclass().method1();
        new Subclass().method2();
    }
}

the code above print out

superclass
superclass

while I expect it to print out

superclass
subclass

Isn't this.method0() refer to the method0 in subclass and print out subclass instead of superclass ?

super represents the instance of parent class. this represents the instance of current class. It will print
superclass
subclass

I ran your code and it gaves me

superclass
subclass

this what should printed every thing seems ok

new Subclass().method1();

executes the method1() of Subclass instance, which in turn calls super.method0(); ie parent class instance's method0() ie Superclass instance method0() .

new Subclass().method2();

executes the method2() of Subclass instance, which in turn calls this.method0(); ie this instance's method0() ie Subclass instance method0() .

super is used to access instance members of the parent class while this is used to access members of the current class.

First of all, it prints out the what you are expecting.

Second,

Isn't this.method0() refer to the method0 in subclass and print out subclass instead of superclass?

this => refer to current object, using it you can use it (kinda of pointer to itself, in general terms )

super => refer to super class object in an hierarchy, usually used to access the hidden members in subclass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM