Java Variables Shadowed Methods overridden concept

匆匆过客 提交于 2020-01-13 05:20:21

问题


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.


回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/12078751/java-variables-shadowed-methods-overridden-concept

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!