Wednesday 2 March 2016

Subclassing and Subtypes

If you look up the add() method of the Container class, you’ll see that it takes a Compo nent object as an argument. In our example, we’ve given it a JButton object. What’s going on? As we’ve said, JButton is a subclass of the Component class. Because a subclass is a kind of its superclass and has, at minimum, the same public methods and variables, Java allows us to use an instance of a subclass anywhere we could use an instance of its superclass. JButton is a kind of Component, so any method that expects a Component as an argument will accept a JButton. The converse, however, is not true. A method signature expecting a particular class will not accept its superclass as a parameter.

0 comments:

Post a Comment