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

Viewed 33

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.

1 Answers

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.

Related