Results 1 to 2 of 2
Thread: Calling Object.method
- 04-11-2009, 12:30 PM #1
Member
- Join Date
- Apr 2009
- Posts
- 5
- Rep Power
- 0
Calling Object.method
Hi,
In a class named 'Kid' I have a property called Parent of type Object. The actual class of this object can by any of a collection of container classes. In my example I've made two classes called Mum and Dad.
Alle possible parent classes have a method called doSomething(). When I try to call this method (Parent.doSomething()) the compiler says it doesn't know this method.
Here is the example:
My question here is: what is going wrong and is there a way to get this done?Java Code:class Mum { Kid myKid; public void doSomething(int What) { ... } public void MakeChild() { myKid=new Kid(); myKid.Parent=this; } ... typicall Mum's stuff } class Dad { Kid myKid; public void doSomething(int What) { ... } public void MakeChild() { myKid=new Kid(); myKid.Parent=this; } ... typicall Dad's stuff } class Kid { Object Parent; public void AskParentToDoSomething() { Parent.doSomething(); } }
-
The compiler has no knowledge that Parent can definitely call the doSomething method, since Parent is an Object, the only methods available to it are Object's innate methods.
One solution (that I don't like) is to cast your Parent variable as a Mum or a Dad.
I think that a better solution is to create an interface, let's call it Parentable, that has one method declared in it, doSomething, and have Mum and Dad implement this interface. Then declare your Parent variable as a Parentable object.
One error I see in your code is that both Mum and Dad's doSomething methods take an int parameter, and you are trying to call the method with no parameter. You'd better fix that.
Similar Threads
-
'Class' Object and calling Static Methods?
By mikeiz404 in forum Advanced JavaReplies: 3Last Post: 01-24-2009, 12:58 PM -
'Class' Object and calling Static Methods?
By mikeiz404 in forum New To JavaReplies: 2Last Post: 01-24-2009, 05:10 AM -
Calling a method in a different class from within a method problem
By CirKuT in forum New To JavaReplies: 29Last Post: 09-25-2008, 07:55 PM -
Calling a method for all instances of an object
By rattle in forum New To JavaReplies: 4Last Post: 04-30-2008, 02:10 PM -
Object from String (calling method dynamically)
By Java Tip in forum Java TipReplies: 0Last Post: 02-16-2008, 09:22 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks