*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inheritance " Watch "Inheritance " New topic
Author

Inheritance

amarkirt saroay
Ranch Hand

Joined: Mar 16, 2008
Posts: 167
public class Test{

public static void main(String []kk){
int y=9;
long b=9;
A obj=new B();
obj.meth(y);
new B().meth(b);
}
}

class A{
public void meth(long u){
System.out.println("parent");
}
}


class B extends A{
public void meth(int aa)
{
System.out.println("child");

}


}

Result is:
parent
parent

why in both cases the parent version of meth gets called?


SCJP-75%
SCWCD-82%
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Note that you're not overriding here. You're overloading. Class B inherits meth(long) from A, and also overloads with its own meth(int).


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Srividhya Kiran
Ranch Hand

Joined: Feb 17, 2008
Posts: 166
Hi,

When methods are overloaded reference type matters. So call to obj.meth(y); will call the super class because the reference type is of the superclass. y is a integer variable so widening occurs to long and you get the output "parent".

Now in this call to new B().meth(b); the variable you pass to the meth() is long and since subclass B has both the versions of meth it will call the class A meth() that takes long as an argument.

Hope this helps you

Srividhya
 
Consider Paul's rocket mass heater.
 
subject: Inheritance
 
Similar Threads
Dynamic Method Dispatch
Overriding
Inheritance
Why Overriding in runtime???
abstrct inner classes