Search code examples
javavariablesinheritanceoverridingshadowing

Java Variables Shadowed Methods overridden concept


I am struggling to understand Variables Shadowed Methods Overriden Concept of inheritance with Java.

Case 1:

class Car{
   public int gearRatio = 8;
   public String accelerate() {  return "Accelerate : Car";  }
}
class SportsCar extends Car{
   public int gearRatio = 9;
   public String accelerate() {  return  "Accelerate : SportsCar";  }
   public static void main(String[] args){
      Car c = new SportsCar();
      System.out.println( c.gearRatio+"  "+c.accelerate() );
   }
}

Output: 8 Accelerate : Sportscar.

Case 2:

public class TestClass{
   public static void main(String args[ ] ){
      A o1 = new C( );
      B o2 = (B) o1;
      System.out.println(o1.m1( ) );
      System.out.println(o2.i );
   }
}
class A { int i = 10;  int m1( ) { return i; } }
class B extends A { int i = 20;  int m1() { return i; } }
class C extends B { int i = 30;  int m1() { return i; } }

Output: 30, 20

So if I understand correctly, the super class variable is always called unless the sub classes variable is called explicitly. But the opposite is true for methods where the sub classes overridden method is called unless the super class is called explicitly.

I would think variables and methods should work the same or there should be a compile error when creating sub classes with the same variables.

Can someone explain if this is correct and why java works like this please.


Solution

  • I would think variables and methods should work the same or there should be a compile error when creating sub classes with the same variables.

    Well, that's simply not the way Java works.

    Variables are not handled polymorphically - there's no concept of "overriding" a variable. Methods, however, are handled polymorphically. Behaviour can be specialized, but not state.

    Note that if your variables are private, as they almost always should be, the situation is never even visible.