Jump to content

INHERITANCE: reason behind that??

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
himanshu

himanshu

    Newbie

  • Members
  • Pip
  • 8 posts
public class Testinheritance
{
public void instancemethod(String...a)
{
System.out.println("instance parent");
}
}
class Testinheritance2 extends Testinheritance
{
public void instancemethod(String a)
{
System.out.println("instance child");
}
public static void main(String args[])
{
Testinheritance obj=new Testinheritance2();
Testinheritance2 obj2=(Testinheritance2)obj;
obj.instancemethod("abc");
obj2.instancemethod("abc");
}
}

output:
instance parent
instance child



please tell me the reason why instance of parent is called in first case

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
The difference may be difficult to spot, but the reason for this is actually quite simple, you're not overriding the function, you're overloading it!

public void instancemethod(String... a) and public void instancemethod(String a) are two different functions, so what the Java compiler will do instead of overriding the function and letting the inherited method take over is it'll produce a "candidate list" of each possible function and try and find the first match. When the object is considered a Testinheritance object, the candidate list starts from the parent object and moves down to the child objects, however when it starts at the child class it goes down the inheritance tree, then circles back and goes to the parent. This means that each reference to the same object will, during compilation, result in two separate candidate lists looking like this:
Testinheritance:
    public void instancemethod(String... a);
    public void instancemethod(String a);

Testinheritance2:
    public void instancemethod(String a);
    public void instancemethod(String... a);
So in each case the result for the Java Runtime will be to go with the first possible match, which in the case of the parent is (String... a) and in the case of the child is (String a). To rectify the problem, simply change the parameters so that they match correctly, and polymorphism will take over.
Wow I changed my sig!

#3
CallinWire

CallinWire

    Newbie

  • Members
  • Pip
  • 8 posts
The answer is due to a messy combination of polymorphism, as well as overloading the method instead of overriding it - both of which can accept one String as a parameter.

EDIT: Ah, so that's why.

#4
himanshu

himanshu

    Newbie

  • Members
  • Pip
  • 8 posts
thnx Zeke