0

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();
    }
}
Dhaval Shah
  • 23
  • 1
  • 5
  • 1
    It sounds like both classes should implement the same interface, basically... And what's `Two`? Did you mean `Main`? And where does the "has-a" relationship come in? Neither A nor B "has" anything else in the normal manner of composition. – Jon Skeet Mar 12 '15 at 11:03
  • ya its my mistake its not "Two" but its "Main" class – Dhaval Shah Mar 12 '15 at 11:28
  • 1
    So please edit the question - and then address the other issues that I asked about. – Jon Skeet Mar 12 '15 at 11:29

2 Answers2

0

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.

LastFreeNickname
  • 1,445
  • 10
  • 17
  • ya its true even i also got this idea but i dont want to add "extend" or "implement" keyword.i want to know which class name should i write in "call method" parameter ? so that i can access n number of class – Dhaval Shah Mar 12 '15 at 11:45
  • As long as they don't share some common base there is no way (except using reflections or similar). I don't see why extend or implement are to be avoided though... – LastFreeNickname Mar 18 '15 at 09:23
  • it was just prototype...why i avoided because of i wanted to call only method that i could use my real project( J2ee using MVC base) let you know in my project all instance variable are private and each Class have a independent – Dhaval Shah Apr 15 '15 at 11:08
0

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

    }

} 
Dhaval Shah
  • 23
  • 1
  • 5
  • Though this works it is a somewhat ugly solution. Using instanceof will get you into other troubles, e.g. minimizes extension or inheritance problems. Consider using extends/implements as suggested in my post. – LastFreeNickname Mar 18 '15 at 09:25