Bring the type of a variable to a child class:
A a = new B(); ((B) a).go();
The problem is that a variable can store an object of class A
and its other heirs, which will not have a go
method. Therefore, it may be necessary to first check whether the variable contains an object of the required class:
if(a instanceof B) { B b = (B) a; b.go(); }
In general, the very fact that you needed a type conversion is a reason to think and work on the logic of the code. Why is a variable declared with type A
? Will there always be a class B
object? Is it necessary to transfer the method to the parent class? Wouldn't it be better to create a method in A
and override its behavior in B
?