• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Inheritance

 
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?

 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
It runs on an internal combustion engine. This ad does not:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic