简体   繁体   中英

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();
    }
}

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.

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();

    }

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM