1

I have been knowing java for a while still sometime i think, i lack few basic concepts. Here is a code which i am trying to run:

   class A{
    int x =10;
    void al(){
        System.out.println("From a");
    }
}
class B extends A{
    int x = 20;
    void al(){
        System.out.println("From b");
    }

    public static void main(String args[]){
        A obj = new B();
        B obj1 = new B();
        A obj2 = new A();
        System.out.println(obj.x);
        obj.al();
        System.out.println(obj1.x);
        System.out.println(obj2.x);
    }
}

and here is the output:

  10
From b
20
10

When i try to call the function al it calles the function in B class. Simple overriding is happening over here. Obj tries to find first in base class then in super class. Now, when i try to access the "X" by object obj it displays "10". Why it is not displaying "20" ?

Alpit Anand
  • 1,213
  • 3
  • 21
  • 37

3 Answers3

4

Your question, specifically, seems to be "why does System.out.println(obj.x); print 10 and not 20?"

obj is declared as an A, and so obj.x will always resolve to the field x that exists within A. There is no dynamic dispatch for fields.

Ultimately, your problem is that there is no field overriding in Java. The field in the super class just gets hidden. When you declare

class A {
    int x = 10;
}
class B extends A{
    int x = 20;
}

and instantiate a B, the object that you get back actually contains two integers. The fact that they have the same name is basically incidental and just makes it slightly harder to refer to them independently, which is usually why you should just choose different names.

Michael
  • 41,989
  • 11
  • 82
  • 128
2

You can't override attributes as you can override methods. "obj" is declared as an object of type A, although the instance is of type B. A.x and B.x are two distincts attributes and not related by any means, although A.al() is overriden by B.al().

1

Instance variables cannot be overridden. They are resolved at compile time as opposed to instance methods.

Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29