Can I make a derived class inherit a derived member from its base class in Java?
Posted
by Eric
on Stack Overflow
See other posts from Stack Overflow
or by Eric
Published on 2010-05-11T18:46:45Z
Indexed on
2010/05/11
18:54 UTC
Read the original article
Hit count: 154
I have code that looks like this:
public class A
{
public void doStuff()
{
System.out.print("Stuff successfully done");
}
}
public class B extends A
{
public void doStuff()
{
System.out.print("Stuff successfully done, but in a different way");
}
public void doMoreStuff()
{
System.out.print("More advanced stuff successully done");
}
}
public class AWrapper
{
public A member;
public AWrapper(A member)
{
this.member = member;
}
public void doStuffWithMember()
{
a.doStuff();
}
}
public class BWrapper extends AWrapper
{
public B member;
public BWrapper(B member)
{
super(member); //Pointer to member stored in two places:
this.member = member; //Not great if one changes, but the other does not
}
public void doStuffWithMember()
{
member.doMoreStuff();
}
}
However, there is a problem with this code. I'm storing a reference to the member in two places, but if one changes and the other does not, there could be trouble. I know that in Java, an inherited method can narrow down its return type (and perhaps arguments, but I'm not certain) to a derived class. Is the same true of fields?
© Stack Overflow or respective owner