Java Variables Shadowed Methods overridden concept

拥有回忆 提交于 2019-12-04 13:30:27

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