1
public class AbcMain {

public static void main(String[] args) {

    Parent p = new Child();
    p.sayHello();
    System.out.println(p.a);
}
}

class Parent{
int a = 10;
public void sayHello(){
    System.out.println("Hello inside parent.");
}
}

class Child extends Parent{
int a = 20;
public void sayHello(){
    System.out.println("Hello inside child. ");
}
}

Output is : Hello inside child. 10

Confused here, It is calling the method of Child() as the instance is of child. Then why it prints a = 10?

1
  • use getter method to get value of a => int getA() , Then override method in Child vlass Commented Nov 25, 2013 at 10:40

4 Answers 4

2

In java method overriding is there. No variable overriding.

Just for testing change the variable name in parent to parentA and see :)

Sign up to request clarification or add additional context in comments.

Comments

1

There is no "overriding" of fields in Java as there is with methods. So you could think that since Child overrode satHello only one instance of the method exists (for the perspective of other classes). However, with fields both instances exist. Therefore Parent.a = 10 and Child.a = 20. Since p is declared as Parent you got 10.

2 Comments

Can you pinpoint this behavior in the JLS? I tried to look it up but failed.
I think the section on "shadowing" might be it: docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.4.1
1

Your Parent pis Child type. Now p is a Child instance. So now you are invoking Child s properties. And Child will override Parent sayHello method.

You should learn about Java polymorphism and inheritance.

Comments

0

Since the object type is Parent, p will have all the characteristics of an Parent. But, since the object created is a Child, any overridden methods in the Child class will be used instead of those in the Parent class. That's why you got Hello inside child as first output.

As, Child is a subclass of Parent, First, Child default constructor will be invoked, and so a is initialized to 20, then there will be a call to Parent default constructor and the value in variable a becomes 10 and thus you will get the second output as 10(The first line in your Child constructor would be super() by default unless you call an overloaded constructor of Child using this()).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.