Reputation: 31
I have a program with 1 parent class and multiple child classes. All child classes have the same method name but doing different functions.I want to be able to call the method from a particular class. For example
class A
{
public void doABC()
{
//do something;
//call Class B's method didABC;
//call Class C's method didABC }
}
class B extends A
{
public void didABC()
{
//does something;
}
}
class C extends A
{
public void didABC()
{
//does something;
}
}
I want to be able to call Class B's didABC
and Class C's didABC
when I want to. How would I do this?
Upvotes: 0
Views: 3788
Reputation:
A quick and dirty implementation of what you want:
interface DoAbc {
public void doAbc();
}
class B implements DoAbc {
public void doAbc() {
//B's implementation
}
}
class C implements DoAbc {
public void doAbc() {
//C's implementation
}
}
class A implements DoAbc {
DoAbc b,c;
A(DoAbc b, DoAbc c) {
this.b=b;
this.c=c;
}
public void doAbc() {
//A's implementation
b.doAbc();
c.doAbc();
}
}
To any design pattern nazi's out there, I know its not a proper implementation of composite design pattern. Its just a quick and dirty implementation for what he wanted to achieve in the question.
Upvotes: 0
Reputation: 1317
public abstract class A
{
public void doABC() { didABC(); }
public abstract void didABC();
}
class B extends A
{
public void didABC() { System.out.println("B::didABC()"); }
}
class C extends A
{
public void didABC() { System.out.println("C::didABC()"); }
}
Now you can do this
A b = new B();
b.doABC(); // Prints "B::didABC()"
A c = new C();
c.doABC(); // Prints "C::didABC()"
If you do not want class A to be abstract, you can also do this
public class A
{
public void doABC() { didABC(); }
public void didABC() { System.out.println("A::didABC()"); }
}
Now you can also do this
A a = new A();
a.doABC(); // Prints "A::didABC()"
Upvotes: 1
Reputation: 68715
Just create an instance of the child class and call method on it.
To call class B's didABC:
B b = new B();
b.didABC();
To call class C's didABC:
C c = new C();
c.didABC();
You can hold the object of child classes in parent class reference and call the methods using that reference also. Whichever class object the parent class will hold it will simply call that class method.
A a = new A();
a.didABC(); // class A method will be called
a = new B();
a.didABC(); // class B method will be called
a = new C();
a.didABC(); // class C method will be called
Upvotes: 4