0

I have a super class Animal and two child class Pig and Dog with a common variable x. Then, I reference a child class via parent class. When I access directly the variable x, then it gives value assigned in parent class(Animal). But, when I access variable x through method getX() then I am getting value assigned in child classes. Why is it coming so?

class Animal {
    
  int x = 10;
  
  public int getX() {
     return x;
  }
  
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {

  int x = 20;
  
  public int getX() {
     return x;
  }
  
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {

  int x = 30;
  
  public int getX() {
     return x;
  }
  
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();
    Animal myPig = new Pig();
    Animal myDog = new Dog();
        
    myAnimal.animalSound();
    System.out.println(myAnimal.getX());
    System.out.println(myAnimal.x);
    
    myPig.animalSound();
    System.out.println(myPig.getX());
    System.out.println(myPig.x);
    
    myDog.animalSound();
    System.out.println(myDog.getX());
    System.out.println(myDog.x);
}
}

I get the output as below:

The animal makes a sound
10
10
The pig says: wee wee
20
10
The dog says: bow wow
30
10
shmosel
  • 49,289
  • 6
  • 73
  • 138
user2755407
  • 348
  • 1
  • 3
  • 15
  • 1
    The subclass's `getX()` is overriding the parent. But fields can't be overridden, only hidden. – shmosel Jun 17 '22 at 19:55

1 Answers1

2

This is an example of field hiding which occurs when both the sub and super class have the same field. Inheritance does not work the same on fields as it does on methods. When referencing a field you will see the field for the type that the variable is defined as.

So in this case

Animal myDog = new Dog();

myDog.x will reference the x field in the Animal class.

While

Dog myDog = new Dog();

myDog.x will reference the x field in the Dog class.

SephB
  • 617
  • 3
  • 6