How is an object handled when it calls a method of its superclass?
I'm foolishly trying to make the concept clear about oscillation (which component can I add to it) and inheritance.
JFrame f = new JFrame();
JFrame g = new JFrame();
f.add(g); // i know that its silly.
it compiles fin because JFrame
is a method container
and add
. His announcement
Component add ( Component comp);
and if i do funny things like above i get an exception saying
adding a window to a container.
What I have analyzed from this is when we call a method that is defined in the above class in the inheritance tree that the object is treated as an object of that above class in the inheritance tree. Like here when we do
f.add(g);
f
is treated as a container because it is add()
not defined in JFrame
, but defined in its parent (or parent to parent more specifically), which is container
. While it is g
considered as a component, because it is JFrame
also Component
.
This seems like a true or false question, but please explain to me technically what I think is correct or not?
But why does the exception say
adding a window to a container.
and why not
adding a container to a component.
how g
is it transmitted add()
how Component
?
My third question is, what is the need for recursive inheritance between Component
and container
?
EDIT why does the exception say so?
source to share
JFrame extends Frame extends Window extends Container extends Component
So indirectly JFrame
is Component
, and jframe.add(jframe2)
is legal, but JFrame
is a child Window
, the message says that adding a window to a container.
is illegal.
How is it checked in the class Container
like this:
/**
* Checks that the component is not a Window instance.
*/
private void checkNotAWindow(Component comp){
if (comp instanceof Window) {
throw new IllegalArgumentException("adding a window to a container");
}
}
source to share
The JFrame hierarchy looks like this:
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
A JFrame
is this Component
, Container
and a Window
.
So why does an exception mean adding a window to a container and not a container to a container ,
because you can add Container
to Container
. Example: JPanel
before JFrame
.
You cannot add Window
to Container
. Because they Window
are intended for top-level components and are not intended to be used inside another component.
And for your third question:
What is the need for recursive inheritance between component and container?
It is not necessary. This is not the case. A Container
is a Component
. But a Component
doesn't always have to be Container
. This is just the layered inheritance you see here for the JFrame. Not recursive.
source to share