chenwei
asked on
How to call a function/method in the child class from thr father class?
I request this question again because I have another problem now.
My code look as follow:
public classFather {
...
protected abstract doNewA();
protected abstract doNewB();
...
doNewA();
doNewB();
...
}
public classChildA extends classFather {
...
doNewA();
doNewB();
...
}
public classChildB extends classFather {
...
doNewB();
doNewA();
...
}
The problem is: If I call doNewA() in ClassA from father class, the doNewA in ClassB is called. How can I avoid it?
My code look as follow:
public classFather {
...
protected abstract doNewA();
protected abstract doNewB();
...
doNewA();
doNewB();
...
}
public classChildA extends classFather {
...
doNewA();
doNewB();
...
}
public classChildB extends classFather {
...
doNewB();
doNewA();
...
}
The problem is: If I call doNewA() in ClassA from father class, the doNewA in ClassB is called. How can I avoid it?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
One more point on the above comment. Consider the following code:
public class Father {
...
public void foo() {
...
doNewA();
...
}
...
public void doNewA() {
...
}
...
}
...
Father a = new ChildA();
a.foo();
Father b = new ChildB();
b.foo();
...
Assume that ChildA and ChildB do not override foo(). Now, the a.foo() call will result in the doNewA() method defined by ChildA being called even though the method call is made in the foo() method defined in Father. Likewise, the b.foo() call will result in the doNewA() method defined by ChildB being called.
public class Father {
...
public void foo() {
...
doNewA();
...
}
...
public void doNewA() {
...
}
...
}
...
Father a = new ChildA();
a.foo();
Father b = new ChildB();
b.foo();
...
Assume that ChildA and ChildB do not override foo(). Now, the a.foo() call will result in the doNewA() method defined by ChildA being called even though the method call is made in the foo() method defined in Father. Likewise, the b.foo() call will result in the doNewA() method defined by ChildB being called.
ASKER
Many thanks to bbkeppler's example codes. But I think carljokl's commment comes near to my points. :-)
...
Father a = new ChildA();
a.doNewA(); // This will call the overridden doNewA() method defined by ChildA.
Father b = new ChildB();
b.doNewA(); // This will call the overridden doNewA() method defined by ChildB.
...
Again, make sure that the object you have a reference to is actually of the class you think it is. ChildA is not aware of ChildB because ChildB is not in its class hierarchy, so it would be impossible for an object whose concrete class is ChildA to exhibit behavior specific to ChildB.