Reputation: 73
Lets say I have Object X and Object B. X is an object of a random class, which in turn creates B, and passes itself on to be stored as a variable in object B.
Now object B, wants to run a method in object X, without knowing what class it is.
Is it possible to call a method in any object, and if a method with that name exist, it runs, and if not, it doesn't. I assume some try/catch can work around that part.
But lets say i have something like this:
public class ObjectB {
public Object parentX;
public ObjectB(Object x) {
parentX = x;
}
public void anyMethod() {
x.runMyMethod();
}
}
In another program I worked with, this was possible with interfaces, and therefore have an idea that it is possible with Java too. However, i cant seem to find the way to set this up. So if the above was the case, how would it be set up, such that ObjectB can call the method on all the classes in my program if that was what i wanted?
Upvotes: 0
Views: 1203
Reputation: 858
Yes its definitely possible.
Define interface MyIntf
, and your Class X
implements it. now in Class B you can assign the object of Class X
(or any class that implements MyIntf
) to parent which of type MyIntf
the you can invoke method with that parent
interface MyIntf
{
void runMyMethod()
}
public class ObjectX implements MyIntf {
void runMyMethod()
{
}
}
public class ObjectB {
public MyIntf parentX;
public ObjectB(MyIntf x) {
parentX = x;
}
public void anyMethod() {
parentX.runMyMethod();
}
}
Upvotes: 2
Reputation: 3430
If you look at the end of this documentation, it tells you about casting. Casting allows the program to assume the object is of a type and attempt to call a method within it.
public void anyMethod() {
((MethodParentObject) this.x).runMyMethod();
}
Upvotes: 0
Reputation: 140525
Now object B, wants to run a method in object X, without knowing what class it is.
Simply doesn't make sense. In order to invoke a method, you need to know its name and the expected parameters. In that sense, class B needs some knowledge. Thus, you would/could do something like
if (parentX instanceof ClassA) {
( (ClassA) parentX ) . someAMethod(bla, blub);
}
if (parentX instanceof InterfaceC) {
( (InterfaceC) parentX ) . someCMethod(bla, blub);
}
In that sense: you might use an interface here; but classes work as well. The key thing is: you need a certain piece of information; otherwise you are simply stuck.
The only other alternative is to look into reflection - then you would not need to know the specific type; as you can inspect parentX
to find out which methods could be called on that object. But reflection is A) an advanced concept and b) intricate in its usage.
Upvotes: 2