1

why we can't override the variables in java , It hides variable

class A {
    int a = 4;
    public void test(){
        System.out.println("Test method of A" );
    }
} 

class B extends A {
    int a = 5;
    public void test(){
        System.out.println("Test method of B" );
    }
    public static void main(String s[]){
        A a= new B();
        System.out.println("Value of a : " a.a );
        System.out.println("Method result " a.test() );
    }
} 

Output ::

Value of a : 4
Mthod result :Test method of B

As the B's class test method get called but variable was accessed from super class reference

matsev
  • 32,104
  • 16
  • 121
  • 156
varsha
  • 304
  • 8
  • 22
  • 3
    `class B extends B` ...what?? – Makoto Feb 06 '13 at 05:52
  • Already explained [here][1] and [here][2] Regards [1]: http://stackoverflow.com/questions/427756/overriding-a-super-class-instance-variables [2]: http://stackoverflow.com/questions/8983002/how-are-the-variables-overridden-in-java – ultraklon Feb 06 '13 at 05:57

3 Answers3

4

It's just how java works. When the code has a B but only 'knows' it has an A, the methods of B will be called but the variables of A will get accessed (since there's no 'method overriding equivalent' for variables). I suggest you wrap variables in getters and setters instead of exposing, so you can control their behaviour in subclasses by overriding the getters and setters.

Patashu
  • 21,443
  • 3
  • 45
  • 53
0

If you want to access variable of Parent class then use
System.out.println( ((A)a).a );
Type cast the object to its parent and then access it

asifsid88
  • 4,631
  • 20
  • 30
0

Assume that you have a method that accepts a parameter of type A

void f(A a) {
     // do something with a.a
}

The writer of the f method has written this method expecting the behavior that is defined by class A. And you want to change this behavior. When you override a method you may or may not change the behavior, and you should not. You can add some other functionality but never change the expected behavior and if you could override a variable you would definitely change the behavior. Check Open/Closed and Liskov Substitution Principles of Object Oriented Design

Mehmet Ataş
  • 11,081
  • 6
  • 51
  • 78