+ 2
What if a inherited variable was redefined in the child class
//Parent class class Animal { protected int legs; public void eat() { System.out.println("Animal eats"); } } // case(1): class Dog extends Animal { Dog() { legs = 4; } } However, what if I declared the variable legs in the dog class // case(2): class Dog extends Animal { int legs = 100; Dog() { legs = 4; } } what will this constructor do? Does the inherited variable override the current declared variable?
1 ответ
+ 15
The "legs" variable in Dog is actually separate from the one in Animal. The constructor assumes you're using the "legs" in Dog. It's as though you wrote it in the constructor like this:
this.legs = 4; //"Use 'legs' from this class"
If you want to refer to the "legs" in Animal, you need to use the keyword "super":
super.legs = 4; //"Use 'legs' from the superclass" (the one you're inheriting from, Animal)
In this scenario, though, all you need is the variable in Animal. There's no reason to redefine it.