Monil
Monil

Reputation: 31

Calling method from child classes having same name - java

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

Answers (3)

user1979424
user1979424

Reputation:

  1. What you are trying to do cannot be achieved using inheritance. A parent will and should never know about what are the subclasses.
  2. You can try to use Composition instead of inheritance. You can read about Composition here

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

anonymous
anonymous

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

Juned Ahsan
Juned Ahsan

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

Related Questions