Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

What is the difference between this and super keywords in Java?

1 Answer

0 votes
by (13.1k points)

Consider this code:
 

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:

animal : eat

dog : eat

animal : eat

The third line is printing animal : eat because we are using super, if we have used this it would have printed dog : eat

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
asked Nov 25, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Apr 2, 2021 in Java by dev_sk2311 (45k points)
0 votes
1 answer
asked Sep 10, 2019 in Java by Nigam (4k points)
0 votes
1 answer

Browse Categories

...