Dhaval Shah
Dhaval Shah

Reputation: 23

How Dynamic Cast Apply in HAS-A Relationship

I want to call both class A Method and Class B method each after. these two class relationship defined as "HAS-A" Relationship....

class A{
    public void getData(){
        System.out.println("Class A");
    }
}

class B{
    public void getData(){
        System.out.println("class B");
    }
}

public class Main {
public static void main(String[] args) {
        A a=new A();
        B b=new B();
        new Main().call(a); //call A Class Method
        new Main().call(b); //call B class Method
    }
    public void call((Class Name??) a){
         a.getData();
    }
}

Upvotes: 0

Views: 52

Answers (2)

Dhaval Shah
Dhaval Shah

Reputation: 23

I got Solution Thanks for helping me.....

class A{
    public void getData(){
        System.out.println("class A");
    }

}
class B {
    public void getData(){
        System.out.println("class B");
    }
}
public class Main{

    public static void main(String[] args) {

        A a=new A();
        B b=new B();


        new Main().call(a);
        new Main().call(b);
    }

    public void call(Object obj)
    {
        if(obj instanceof A)
            ((A) obj).getData();

        if(obj instanceof B)
            ((B) obj).getData();

    }

} 

Upvotes: 0

LastFreeNickname
LastFreeNickname

Reputation: 1455

You can make A and B extend Upper, with Upper either being an upper class or an interface. In both cases it should have the method getData(), so your call()-method can access it.

Upvotes: 0

Related Questions