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 class in 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 extends keyword 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 super keyword 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 super keyword 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 final keyword 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 final method cannot be overridden by subclasses.
  • A final variable is a constant and its value cannot be changed once initialized.

Visibility and Inheritance

  • Protected members (fields and methods declared with the protected keyword) 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 Object class if no explicit superclass is defined. This means that every class you create in Java is a subclass of the Object class.
  • The Object class includes methods like toString(), equals(), hashCode(), and clone(), which can be overridden as needed in any class.