If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?

Member variables cannot be overridden like methods. The number variables in your classes Beta and Gama are hiding (not overriding) the member variable number of the superclass.

By casting you can access the hidden member in the superclass.


Fields can't be overridden; they're not accessed polymorphically in the first place - you're just declaring a new field in each case.

It compiles because in each case the compile-time type of the expression is enough to determine which field called number you mean.

In real-world programming, you would avoid this by two means:

  • Common-sense: shadowing fields makes your code harder to read, so just don't do it
  • Visibility: if you make all your fields private, subclasses won't know about them anyway