-1
class A 
{
    protected int i=10;
}
class B extends A
{
    protected int i=15;
}
public class Test extends B
{
    public static void main(String a[]) 
    {
        A obj=new Test();
        System.out.print("i="+obj.i);
    }
}

It's output is i=10, but how?

How is the memory allocation for the object will take place.

halfer
  • 19,824
  • 17
  • 99
  • 186
Amit Kumar
  • 33
  • 3
  • 1
    Because you declared it to be of type `A` – JonK Aug 11 '15 at 08:14
  • From The Java Programing Language 4th edition: "beyond being accessible within the class itself and to code within the same package (see Chapter 18), a protected member can also be accessed from a class through object references that are of at least the same type as the class - that is, references of the class's type or one its subtypes.". Section 3.5 - What `protected` Really Means - of the book goes into more detail if you are interested in knowing more. http://dl.acm.org/citation.cfm?id=1051069 – Binil Thomas Aug 11 '15 at 08:26
  • Because the declaration is of the class A, and you are accessing the var i directly, if you had a getI() in both classes for example, the result would be 15. – fdam May 17 '16 at 20:31

4 Answers4

4
A obj=new Test();

Means, you are accessing the members of Class A and executing the methods of Test(polymorphism).

I suggest you to read the official docs on inheritance and polymorphism to understand deep.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

Polymorphism is linked to objects not references. Since you are using a reference of type A, you will get A.i if you have method getI() in A and override it in B, then call obj.getI(), then you will get B.i's value

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

In java, Variable Overriding is not there. We have the concept of method Overriding.

In your code

A obj=new Test();

You can able to access members of A. If you have overridden same method in both the classes (Parent and Child). And you are calling that method with obj. This time you will get output from Child class overridden method. this is the concept of Polymorphism.

0

Line 1: A a = new A();

the method existence will be checked in A class and the method will be called from A class also.

a.g();//A class method will be called
 System.out.print("i="+a.i);//A class i will be accessed

Line 2: A b = new B();

the method existence will be checked in A class and the method will be called from B class.

b.g();//B class method will be called and it will also check that it is` available in A also or not if not then compile time error.
System.out.print("i="+b.i);//A class i will be accessed
Piyush Mittal
  • 1,860
  • 1
  • 21
  • 39