-2

when showName() is called with Rabbit class object it calls the showName() inherited from Animal class and printing Animal class name variable.

  class Animal{ 
  String name="animal";
  
  void showName() {  
    System.out.println(this.name);
  }

}

class Rabbit extends Animal {
  String name="rabbit";
}


public class Main
{
    public static void main(String[] args) {
        Animal a = new Animal();
        a.showName();
        Rabbit r = new Rabbit();
        r.showName();
    }
}

output: animal animal

dave
  • 19
  • 5
  • 1
    Overriding works only for methods, not for fields. – Henry Jan 10 '21 at 07:07
  • 1
    Does this answer your question? [Overriding member variables in Java ( Variable Hiding)](https://stackoverflow.com/questions/10722110/overriding-member-variables-in-java-variable-hiding) – Omkar76 Jan 10 '21 at 07:10

1 Answers1

0

When you call a method on an instance of a class, Java will first try and find the method in the subclass, and if not found, it will try and look in the superclass.

In your code, when you call r.showName(), it will first check for that method in the Rabbit class, and since it does not find it there, it checks the superclass Animal. It finds it in Animal, so it runs the method it finds there.

If you want r.showName() to say rabbit, you have to override the method in the Rabbit class.

Kirit
  • 305
  • 1
  • 3
  • 8