Why use the keyword "this" to get superclass methods

I have seen Java examples that use the keyword thisto get superclass methods. Example this.superClassMethod(). In the usual case, we would use super. Can someone help clarify an example of why the developer used thisinstead super? Thank.

+5
source share
4 answers

There is no difference between this.method()and super.method()until the specified method()is overridden in the caller class.

For example, when

class SuperClass {

    public void method() {
        System.out.println("SuperClass");
    }

}

class SubClass extends SuperClass {

    public SubClass() {
        method();
        this.method();
        super.method();
    }

}

Call

new SubClass();

Print

SuperClass
SuperClass
SuperClass

Till

class SuperClass {

    public void method() {
        System.out.println("SuperClass");
    }

}

class SubClass extends SuperClass {

    @Override
    public void method() {
        System.out.println("SubClass");
    }

    public SubClass() {
        method();
        this.method();
        super.method();
    }

}

Call

new SubClass();

Print

SubClass
SubClass
SuperClass

At the same time, there is no difference between this.fieldand super.fielduntil the specified fieldone is hidden in the class of the caller.

For example, when

class SuperClass {

    protected String field = "SuperClass";

}

class SubClass extends SuperClass {

    public SubClass(String field) {
        System.out.println(field);
        System.out.println(this.field);
        System.out.println(super.field);
    }

}

Call

new SubClass("parameter");

Print

parameter
SuperClass
SuperClass

Till

class SuperClass {

    protected String field = "SuperClass";

}

class SubClass extends SuperClass {

    private String field = "SubClass";

    public SubClass(String field) {
        System.out.println(field);
        System.out.println(this.field);
        System.out.println(super.field);
    }

}

Call

new SubClass("parameter");

Print

parameter
SubClass
SuperClass

: methods() , fields .

+17

this . , . , , , .

(, , ), , , .

, , IDE this.: -)

+5

super , .


1)
2) SO

, super(), , this(), , .

class Animal {
  void eat() {
    System.out.println("animal : eat");
  }
}

class Dog extends Animal {
  void eat() {
    System.out.println("dog : eat");
  }
  void anotherEat() {
    super.eat();
  }
}

public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = new Dog();
    d.eat();
    d.anotherEat();
  }
}

animal : eat
dog : eat
animal : eat

- ": ", super.eat(). this.eat(), ": ".

+3

oracle/sun java . java\awt\Event.java #translate

public void translate(int dx, int dy) {
    this.x += dx;
    this.y +=     
}

( src.zip . ..java , /param, .

( x) , , / .

. , , . , , , , .

, , . , - , .

0

All Articles