Anoop Kanyan
Anoop Kanyan

Reputation: 618

Java - inheritance

class Base
{
        int x=1;
    void show()
    {
        System.out.println(x);
    }
}
class Child extends Base
{
    int x=2;
    public static void main(String s[])
    {
        Child c=new Child();
        c.show();
    }
}

OUTPUT is 1. The method show is inherited in Base class but priority should be given to local variable and hence the output should have been 2 or is it that the compiler implicitly prefixes super before it??

Upvotes: 1

Views: 126

Answers (4)

Jindra Helcl
Jindra Helcl

Reputation: 3736

Since you are not overriding the show method in Child, the Base's version will be used. Therefore it cannot see the x variable you defined in Child. Your IDE (if you are using one) should give you a warning that you are "hiding a field".

You can achieve the expected functionality by setting the x of a Child object after instantiating it. Try:

class Base
{
    int x = 1;

    void show() {        
        System.out.println(x);
    }
}

class Child extends Base
{
    public static void main(String s[]) {

        Child c = new Child();

        c.show();
        c.x = 2;
        c.show();
    }     
}

This should yield 1 and then 2.

EDIT: Note this works only when the x field is accessible from the main function.

Upvotes: 1

christopher
christopher

Reputation: 27346

With one Show Method

class Child extends Base
{
    public Child(int x)
    {
        super(x); // Assumes a constructor in the parent that accepts an int.
        // or
        super.x = x;
    }
}

Then you will only need the one show() method.

With Two Show Methods

You override the functionality of the superclass, in it's child classes, as follows:

class Child extends Base
{
    public void show()  
    {
       // OVerrides the code in the superclass.
       System.out.println(x);
    }
}

Which should you prefer?

You're trying to override functionality, so you should favour the second option.

Upvotes: 1

Math
Math

Reputation: 3396

Base class doesn't know about Child class, so the show() method will never call the variable from it's subclass.

So, if you want to show the x from the subclass override the show() method by reimplementing it in the Child class.

Upvotes: 0

duffymo
duffymo

Reputation: 308763

No, it's because the Child didn't override the show() method. The only one available is the one from Base, which displays its version of x.

Try it this way - it'll display 2:

class Base
{
        int x=1;
    void show()
    {
        System.out.println(x);
    }
}
class Child extends Base
{
    int x=2;
    public static void main(String s[])
    {
        Child c=new Child();
        c.show();
    }
    void show()
    {
        System.out.println(x);
    }
}

Upvotes: 2

Related Questions