简体   繁体   中英

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.

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.

In java there is no Instance variable overriding concept and variables are not polymorphic as methds.

So in your case, if you use :

Car c = new SportsCar();  // c is Object reference of type Car
System.out.println( c.gearRatio+"  "+c.accelerate() );

c.gearRatio refers to the gearRatio in Car and not from SportsCar . In case of method c.accelerate() , method is overridden in SportsCar and it is SportsCar object, so SportsCar.accelerate() is called.

public static void main(String args[ ] ){
  A o1 = new C( );  // object reference is of type A and object is C
  B o2 = (B) o1;   // object of C can be type casted to B as B is parent to C
  System.out.println(o1.m1( ) ); // C.m1() will be called.  
  System.out.println(o2.i );   // o2 is type B, so B.i will be printed
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM