Java : Polymorphism, Inheritance, and Encapsulation
To record a bit of my rough understanding of polymorphism, inheritance, and encapsulation in Java.
Polymorphism
- Operate different object / instances under the same interface
- Implementation examples
- abstract class
- Contains at least one abstract method
- Leave implementation to inherited classe(s)
- No multiple inheritance
- Cannot have final declaration
- Cannot be instantiated
- Contains constructor(s)
- interface
- After compilation
- Properties are automatically added with
public static final
(constant) - Methods are automatically added with
public abstract
(abstract) - All methods must be implemented
- Does not contain constructor
Inheritance
- Let the inherited class automatically own the attributes and methods of the super class, and the inherited class can use them directly
- Implementation examples
- No multiple inheritance
- Use
super()
keyword- To call the super class method
- To call the super class constructor
- If there is method overloading, refer to the constructor parameter of
super()
- When constructors are called, things defined by super class are used directly to reduce repeated code
- If there is method overloading, refer to the constructor parameter of
- Subclass can override methods of super class
- Methods modified with final cannot be override
- Method names, return types, and number of parameters must be the same
- The access modifier of subclass methods must be less strict than those of the sub class methods
- Override from less strict to more strict
Encapsulation
- Hide implementation details
- For example, the simplest is
Getter
andSetter
- To handle the private attributes: to control, protect, and limit the access
- Common use scenario is to set the setter's attribute validation logic.
- All methods implemented must be non-static
Class {
private name;
// getter / setter called in the main class
}
I think that's it.