Java Inheritance – Accessing Child Methods via Casting in Java

inheritancejavaobject-orientedtype casting

I have several classes Parent and Child1Child9 implemented in Java. Parent is an abstract class, containing all the common variables of the child classes (a lot, which is the main reason why I made Parent an abstract class and not an interface), some abstract and some implemented methods.

Some of the child classes have custom methods which are specific to them. So often I find myself calling a child method using downcasting:

Parent p = new Child1();
((Child1) p).child1SpecificMethod();

Somehow I have the feeling that this is bad OOD practice, but I am not quite sure if that really is the case respectively how to improve the design.

– Edit –
What I probably should change anyway is the fact that I use the Parent class for organizing many (for now) common variables, making them (or a container object) members of the concrete classes.

Best Answer

This is not only bad practice, this is unnecessary complicated.

Why do you use inheritance in general?

When you use inheritance, you have a common set of behaviour, which you want to make available for many different carriers. This includes class inheritance as well als interface inheritance. The heir, so to speak, is oftentimes a specialization of the class from whom it inherits; which is mainly true for class inheritance.

Think of a class car and a subclass porsche (the typical is a-relationship). You have general behaviour like starting/stopping engine, steering and so on. If you treat a porsche like a car, you are bound to this aspect of its behaviour. If you know, that you only want a porsche and only deal with it as a porsche, it is redundant to instantiiate a porsche as a car and get porsche-behaviour via casting.

Polymorphism makes sense the other way around:

You have a porsche and need to treat it from the aspect of a car; e.g. driving

As long as your porsche accepts steer left, steer right, shift up, shift down, etc. you could make use of polymorphism/substitution one for the other.

It is better, to instantiate your objects in their specialized form. Then you could make the most of polymorphism and use it only when you need it.

That said: Parent p = new Child1(); makes no sense for me.

Edit: I would implement porsche different (via composition), but for the sake of the example, it is a car.

Related Topic