0

If I have a subclass in Java and both (parent and son) for some reason must have same variable (String department), then If I create an instance like :

Parent var1 = new Son();
System.out.println(var1.department);

This will print what value in Parent.department is. But if I have a method getDepartment() overridden (in both class), then

System.out.println(var1.getDepartment());

This will print what return from Son.getDepartment is.

So, why virtual method invocation does not apply in same way to variables ?

why is necessary to do Downcast as follow, in order to take variable from Son Class instead of Parent class

Parent var1 = new Son();
Son varSon = (Son)var1;
System.out.println(varSon.department);

doing in this way now will print what value in Son.department is.

Hugo Carmona
  • 294
  • 1
  • 3
  • 9

0 Answers0