Java Inheritance... Confused -



Java Inheritance... Confused -

i have abstract parent class has multiple children. i'd kid able have variable same every instance of child. i'd prefer not pass constructor kid tell it's name because seems silly when can hardcoded. i've read doing next "hides" parents instance variable , doesn't work want.

public abstract class parent { public string name = "the parent"; public getname(name); } public class child1 extends parent { public string name = "jon"; } public class child2 extends parent { public string name = "mary"; } child1 c = new child1(); c.getname(); // want homecoming "jon", instead returns "the parent".

to clear, want c.getclass().getname() don't want have result of dependent on class name, rather on hardcoded value.

thanks

depending on you're trying for, there couple of solutions. 1 create kid classes provide name parent:

public abstract class parent { protected parent(string name) { this.name = name; } public getname() {return name;} } public class child1 extends parent { public child1() { super("jon"); } } public class child2 extends parent { public child2() { super("mary"); } }

another utilize method inheritance like isaac truett suggests.

java inheritance

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -