Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
Button extends Component. So does TextField.
For this reason. this is allowed.
And we can call setBackground and other such Component methods.
A subclass reference can be stored as a superclass reference.
If however we want to call Button methods like getLabel and setLabel, we can NOT use the Component reference.
We need a Button reference. This is possible, because the actual data type of the instance, Button, is retained. We CAST the Component reference to Button reference.
The actual data type of an instance is set only where the keyword new is used.
In this example the data types are obvious, but if you have a superclass reference where you need to know if it actually refers to an instance of, say, TextField, you can use the keyword instanceof, to make sure.
Cast to a TextField reference.
Call TextField's setEchoChar method.
Call TextField's inherited getText and setText methods. (Inherited from TextComponent.)
The Component references can be passed as parameters to Container's add method,
because it has been coded as such.