Creating Superclasses and Subclasses
Creating Superclasses and Subclasses
Defining Superclasses
- A superclass (also known as a parent or base class) is a class from which other classes can inherit properties and behaviours.
- When defining a superclass, your focus should be on common characteristics that the subclasses can share.
- Properties of a superclass can include fields (the state of the object) and methods (the behaviour of the object).
- Superclasses use the keyword
classin their definition, just like any other class.
Defining Subclasses
- A subclass (also known as a child or derived class) is a class that inherits properties and behaviours from a superclass.
- Subclasses are defined using the
extendskeyword followed by the superclass name. - In addition to inherited properties and behaviours, subclasses can also have their own unique fields and methods.
- Subclasses can also override methods from the superclass, allowing them to provide a different implementation.
The super Keyword
- The
superkeyword refers to the immediate parent class. It can be used to call the constructor, methods and access fields from the superclass. - The syntax for calling the superclass constructor is
super(). It must be the first statement in the subclass constructor. - The
superkeyword can also be used to call methods in the superclass that have been overridden in the subclass. For example,super.methodName().
The final Keyword
- The
finalkeyword can be used to prevent a class from being subclassed, a method from being overridden, or a variable from being re-assigned. - When a class is declared
final, it cannot be extended, effectively making all of its methods final as well. - A
finalmethod cannot be overridden by subclasses. - A
finalvariable is a constant and its value cannot be changed once initialized.
Visibility and Inheritance
- Protected members (fields and methods declared with the
protectedkeyword) of a superclass can be accessed directly in its subclasses, regardless of the package the subclasses are in. - Private members of a superclass cannot be accessed directly in the subclass. Instead, getters and setters should be used.
- Public members of a superclass can be accessed anywhere, including in subclasses.
Understanding Object Superclass
- In Java, all classes implicitly extend the
Objectclass if no explicit superclass is defined. This means that every class you create in Java is a subclass of theObjectclass. - The
Objectclass includes methods liketoString(),equals(),hashCode(), andclone(), which can be overridden as needed in any class.