Lesson TwelveSuperclasses and subclassesWhen you are using superclasses and subclasses, it is important to remember that two constructors execute. The base, or parent, class constructor MUST execute prior to the extended, or child, class constructor. For example: When you run this application, you will get both sentences printing in order from base class to subclass. If you don't provide a constructor, Java will provide one for you. You can use as many constructors as you want, however, if you create one, you can never use the automatic version. When a superclass constructor requires arguments, you need a constructor for each subclass. You call a superclass constructor by typing super(all, your, arguments);. With the exception of comments, super() must be the first line in the subclass constructor. Below are three programs that show how all this comes together. The first is the "parent" or "superclass" program.
public class EventWithConstructorArg This next one is the "child" or "subclass" program that passes arguments to the parent program.
public class DinnerEventWithConstructorArg extends EventWithConstructorArg This last programs shows how the child program sends the arguments to the parent class. Although there are more things programmed than are being asked of this program, it is only the statments that are relavent to this lesson that are being called in this program.
public class UseEventsWithConstructorsArg Once compiled and error-free, your programs should have this output:
Simple event: You can access a parent class' methods by using the keyword super. To do this, you would need to type is as this: super.anySuperclassMethod(); A child class cannot inherit "private" parent class members. They can, however, inherit protected data. This is called information hiding. Private data and methods cannot be extended from a superclass. If a superclass has data or methods that are protected, then a child class can use the inherited protected data or methods. In other words, if you could use private data outside of a superclass, the idea of information hiding would be lost. Question: Wow!! Inheritance seems to make things easier to program. Is there anything more about inheritance that I should know? Answer: Yes, there is. Next we'll learn about abstract classes and dynamic method binding.
If you have a question about any of the lessons, feel free to ask. |