Difference between “this” and“super” keywords in Java

前端 未结 9 1849
你的背包
你的背包 2020-11-27 03:00

What is the difference between the keywords this and super?

Both are used to access constructors of class right? Can any of you explain?

9条回答
  •  生来不讨喜
    2020-11-27 03:37

    Lets consider this situation

    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();
      }
    }
    

    The output is going to be

    animal : eat
    dog : eat
    animal : eat
    

    The third line is printing "animal:eat" because we are calling super.eat(). If we called this.eat(), it would have printed as "dog:eat".

提交回复
热议问题