What's wrong with this example of Java property inheritance? -


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. sad.

fields aren't polymorphic. you've declared 3 entirely distinct fields... ones in cat , dog shadow or hide 1 in animal.

the simplest (but not best) way of getting current code remove sound cat , dog, , set value of inherited sound field in constructor cat , dog.

a better approach make animal abstract, , give protected constructor takes sound... constructors of cat , dog call super("meow") , super("woof") respectively:

public abstract class animal {     private final string sound;      protected animal(string sound) {         this.sound = sound;     }      public string speak(){         return sound;     } }  public class cat extends animal {     public cat() {         super("meow");     } }  public class dog extends animal {     public dog() {         super("woof");     } } 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -