Inheritance.java
public class InheritanceExample {
static public void main(String[] args){
Cat c = new Cat();
System.out.println(c.speak());
Dog d = new Dog();
System.out.println(d.speak());
}
}
Animal.java
public class Animal {
protected String sound;
public String speak(){
return sound;
}
}
Cat.java
public class Cat extends Animal {
protected String sound = "meow";
}
Dog.java
public class Dog extends Animal {
protected String sound = "woof";
}
Output:
null
null
My animals cannot speak. So sad.
Fields aren't polymorphic. You've declared three entirely distinct fields... the ones in
Cat
andDog
shadow or hide the one inAnimal
.The simplest (but not necessarily best) way of getting your current code is to remove
sound
fromCat
andDog
, and set the value of the inheritedsound
field in the constructor forCat
andDog
.A better approach would be to make
Animal
abstract, and give it a protected constructor which takes the sound... the constructors ofCat
andDog
would then callsuper("meow")
andsuper("woof")
respectively:You're shadowing the field inherited from
Animal
. You have a few options, but the prettiest way of doing it is passing the sound in the constructor:This way, you can make sure that an
Animal
always has a valid sound, right from construction.The Java(TM) way is to declare the protected String getSound() in Animal.java and implement it in the subclasses.
You're hiding fields. The
sound
inAnimal
is not the sameString
as thesound
inCat
.One possible solution is to create a constructor and there simply say
instead of in the class body saying
to set the field.
You didn't allow your animals to speak! you should do like this :
Cat.java:
Dog.java:
just because there are two members "sound" in Cat or Dog,and the one inherited from Animal is hidden without value(so it prints null);another is special to Cat or Dog,which is assigned a value. So you should use the pointer 'this' to quote the original member 'sound'.
You cannot override class fields, only methods. The
sound
field in yourDog
andCat
classes is actually hiding thesound
field in theAnimal
superclass.You can, however, access superclass fields from subclasses, so you could do something like this:
Or, you can make the
Animal
class abstract, and declare thespeak
method abstract too, then define it in subclasses: