Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have 3 classes:

public class Alpha {     public Number number; }  public class Beta extends Alpha {     public String number; }  public class Gama extends Beta {     public int number; } 

Why does the following code compile? And, why does the test pass without any runtime errors?

@Test public void test() {     final Beta a = new Gama();     a.number = "its a string";     ((Alpha) a).number = 13;     ((Gama) a).number = 42;      assertEquals("its a string", a.number);     assertEquals(13, ((Alpha) a).number);     assertEquals(42, ((Gama) a).number); } 
like image 969
Kiril Kirilov Avatar asked Feb 23 '12 14:02

Kiril Kirilov


People also ask

Can a subclass have a method with the same name?

If your subclass defines a method with the same name and signature as a method in its superclass, the method in the subclass overrides the one in the superclass. Thus, the subclass does not inherit the method from its superclass.

What happens if superclass and subclass having same field name?

When declaring a variable in a subclass with the same name as in the superclass, you are hiding the variable, unlike methods which are overwritten.

Can a subclass add new fields?

You can declare new fields in the subclass that are not in the superclass. The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.

Can you override a field?

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.


2 Answers

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.

like image 91
Jesper Avatar answered Sep 24 '22 01:09

Jesper


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
like image 35
Jon Skeet Avatar answered Sep 23 '22 01:09

Jon Skeet