Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance

 
amarkirt saroay
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Srividhya Kiran
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic