aspose file tools*
The moose likes Beginning Java and the fly likes Inheritance. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inheritance." Watch "Inheritance." New topic
Author

Inheritance.

Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Hi.
I created this code and compiled it.


When I compiled it, the compiler reported the error:
Wrong number of arguments in method.
s.methodTwo(999);
1 error.
I imagine the error occurs because the compiler thinks that I'm calling Super's methodTwo. Surely the line commented with x would reveal to the compiler that I'm now referencing the t11 object? In other words, both t11 and s reference the same Test11 object. Please help.

[This message has been edited by Gaia Nathan (edited August 16, 2001).]
[This message has been edited by Cindy Glass (edited August 16, 2001).]
Mikael Jonasson
Ranch Hand

Joined: May 16, 2001
Posts: 158
Well, there are actually a few things to consider here.
First of all: 999 is considered an integer value so there is no coresponding methodTwo.
Since the methodTwo in super and test11 has different parameters, it is not a case of overriding, but overloading.
Why do you declare Super s twice in test11 (once as a method parameter, and once as a "local" variable in main.
Why do you do the "Super s = new Super();". That instance will only be GC'd (maybe) at the next line.
Hope this clears up some of your ?'s.
/Mike
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

This is a case of using a 'base class pointer' (sorry, i slipped into c++ there) to refer to a subclass.

All the compiler knows is that s is of type Super.

Then you make s refer to an instance of a subclass, which is allowed. But when you do this, the only methods it knows about are those in the base class. Until you explicity cast the reference, you can't see the overloaded method.gives us:
[This message has been edited by Mike Curwen (edited August 16, 2001).]
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Thanks Mikael and Mike.
Mike, your example is very clear. To iterate:
Although s references a Test11 object(t11), the compiler still views it as a SuperClass object variable, and hence only 'sees' the base class methods. With the explicit cast ( (Test11)s ), the overloaded methodTwo in the subclass is able to be called using the s object variable.
Hope I got it right.
Thank you again.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Inheritance.