1
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??

1
  • 1
    Polymorphism does not apply to fields. Commented Nov 25, 2013 at 15:57

4 Answers 4

2

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); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

0

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.

Comments