I have an arraylist of an interface named Component. There is another class named Frame that extends component as follows: Component (interface) > AbstractComponent (abstract class) > AbstractContainer (abstract class) > OrganizedContainer (class) > Frame (class)
Everything in the component arraylist goes to a renderer to be rendered. I want to be able to access the methods of the Frame object from the AbstractContainer class. Is this possible without declaring the method in the Component interface?
A Class implements an interface. A Class extends another Class. An Interface extends another interface. This is the convention in java and I mentioned as in your question you have said your class extends the interface Component
.
Frame<<concrete class>> extends OrganizedContainer extends AbstractContainer extends AbstractComponent implements Component<<interface>>
Now coming to your question. Is it possible from inside the AbstractContainer
Class to access the method which are only defined in Frame
? Yes it is possible.
How ? In the parent just typecast the (Frame)this.methodInFrame()
and to avoid some other sub class object being the currently referred by this
, you need to use the instanceof
operator. so its like
if(this instanceof Frame){
(Frame)this.methodInFrame();
}
Is it a good practice ? No not at all, Super class should not be dependent on its sub classes. This increases coupling in your program and leads to maintenance issues. What if you have or plan to have or may have in future any more concrete sub classes ? When you modify the Frame
your super classes needs to be modified and due to that your newly added subclasses may need modification. Also this leads to issues which may be runtime issues. when ever you use instanceof
note that it is a code smell, you must have very good reason to use it.