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