• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is going on here

 
Timmy Ryan
Ranch Hand
Posts: 63
IntelliJ IDE Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Derived extends Base
{
public static void main(String[] args)
{
Base b = new Derived ();
b.someMethod();
}
void someMethod()
{
System.out.println("one");
}
}

class Base
{
}

Why cant the compiler find the 'b.someMethod()' method?
[ December 09, 2007: Message edited by: Bear Bibeault ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please be sure to use UBB code tags when posting code to the forums. Unformatted code is extermely hard to read and most people will just go elsewhere. Please read this for more information.

You can go back and change your post to add code tags by clicking the .
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by John Reilly:
...Why cant the compiler find the 'b.someMethod()' method?

Because 'b' is a variable of type Base, and Base has no such method. To use someMethod, you would need to either downcast the reference back to type Derived, or declare the method in Base.
 
nico dotti
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So when you override a method using the polymorphism of, per your example:
Base b = new Derived();
b.foo();// foo has to be defined in Base!

Here's the confusion (conquer this and you'll have it!):
The reference variable (in this case the Base or Super) provides for what method CAN be called. So you have to have it defined or implemented in the Base or Interface. However, IF IT IS defined in the base/super class, it's the object instance that's being pointed to (in your case the subclass) that will be the method ran. So it's a bit confusing because the reference decides if the method is allowed while the object BEING referenced determines which code will run (after it passes the first condition of being available). And of course this is easier if I try to code it for you:


I did the code off the top of my head so there my be a mistake but the fact is that you have to define a method in the Super/Base/Parent for you to actually be overriding anything in the Sub/Derived/Child. In your example, you actually have a method that is unique to the child class so no overriding is even taking place. Ok, I've described this about as many ways as I can think...let me know if it's making sense now
 
Timmy Ryan
Ranch Hand
Posts: 63
IntelliJ IDE Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Nico,

It makes sense now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic