Ian McGrath
Ian McGrath

Reputation: 1012

Explanation of the output

The question might be a very basic one. I am new to Java so please bear with me. My code:

class A
{
     int b=10;

     A()
     {
          this.b=7;
     }

     int f()
     {
          return b;
     }
}

class B extends A{ int b; }

class Test
{
     public static void main(String[] args)
     {
          A a=new B();
           System.out.println(a.f());
     }
}

Why is the output 7? Doesn't class B get its own instance variable b?

Upvotes: 1

Views: 95

Answers (2)

Mik378
Mik378

Reputation: 22171

Your type reference is A:

A a = new B(); 

Thus instance fields/static fields and static methods will be provided from A, as long as concerned method (in your case f()) isn't overriden by B.

In other languages, as Scala, variables can be redefined in subclasses and targeted even from a supertype reference.

Upvotes: 0

Karthik T
Karthik T

Reputation: 31952

It would but the function f can only see the version of b that is in A. Thus the function returns 7.

If you were to copy the function f into the class B you would see the member b of the class B being returned.

As Hiding instance variables of a class explains, Java variables are not polymorphic. The 2 b variables are 2 different variables as you would expect, but when you call the function A.f it can only see the one b variable that A has. So it returns A.b and NOT B.b.

So to answer your question, class B DOES get its own instance variable b, and it is completely independant of A.b but you currently have no way to access it so you cannot see its value.

Upvotes: 6

Related Questions