简体   繁体   中英

Java Superclass Methods: keyword "this" vs "super"

Say I have:

public class A<T>{
    public void print(){
        System.out.println("Hi");
    }
}

and I create

public class B extends A<Integer>{

}

What is the difference between accessing the print() function in A via super.print() versus this.print()? Both seem to access the method.

super.print() is intended to call the superclass method from the child method. If you wanted to, for example, override print in A to say something else and print "Hi" , you could write

public void print() {
  super.print();
  System.out.println("I'm a B, by the way :)");
}

Calling this.print() here would infinitely call the same function which would hang your program.

Now, you can use super in other contexts, but you really shouldn't. What it says is "ignore the current class and make a static call to my parent's implementation". That makes sense (and is useful) in an overridden method. It's just confusing in other contexts.

So, if this.print() makes sense (which it does unless you're overriding print ), you should use that, as it's what everyone will expect. super.print() should only be used in an override of the print method, since you have no other option.

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