I am trying to wrap my mind around something in java. When I pass an object to another class’ method, can I not just call any methods inherent to that object class?
What is the reason code such as the example below does not compile?
Thank you,
class a { public static void myMethod(Object myObj) { myObj.testing(); } } class b { public void testing() { System.out.println ('TESTING!!!'); } } class c { public static void main (String[] args) { b myB = new b(); a.myMethod(myB); } }
Edit: The reason I have left the parameter in myMethod as type Object, is because I would like to be able to pass in a variety of object types, each having a testing() method.
If you would like to pass in a variety of objects with
testing()methods, have each object implement aTestableinterface:Then have
myMethod()take aTestable.Edit: To clarify, implementing an interface means that the class is guaranteed to have the method, but the method can do whatever it wants. So I could have two classes whose
testing()methods do different things.