November 8, 2023
Subclassing is the practice of creating a new class, known as a subclass, that inherits attributes and methods from another class, referred to as the superclass. This relationship allows for polymorphism and code reuse, where subclasses can override or extend the functionality of their superclasses.
Defining a base class
Extending the base class to create a subclass
To create a subclass, use the
extends keyword followed by the base class name. The subclass can then add its own properties and methods or modify existing ones.
Overriding methods in a subclass
Subclasses can override methods of their superclass to provide specialized behavior. The
super keyword is useful to call functions on an object's parent.
Using the subclass
Once the subclass is defined, you can create instances of it and use them just like any other class:
Handling constructors and method chaining
super() before using
this. This calls the parent class' constructor, ensuring that the subclass is properly set up. Here is an example:
Static methods and properties
Private and protected members
# prefix. These private fields are not accessible outside the class they are declared in, not even by subclasses.
Subclassing built-in classes
Mixin patterns for multiple inheritance
Best practices for subclassing
When subclassing, it's important to ensure that subclasses are a logical extension of their superclass. They should represent a more specific version of the superclass and adhere to the Liskov Substitution Principle, which states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
How to Truncate Date in MySQL