Polymorphism and Related Concepts in Java
Polymorphism in Java manifests as object polymorphism and behavior polymorphism, occurring under inheritance or implementation relationships.
package polymorphism;
class Person {
public void move() {
System.out.println("Person moves.");
}
}
class CollegeStudent extends Person {
@Override
public void move() {
System.out.println("College student moves quickly.");
}
}
class Instructor extends Person {
@Override
public void move() {
System.out.println("Instructor moves with effort.");
}
}
class PolymorphismDemo {
public static void main(String[] args) {
Person p1 = new Instructor();
p1.move(); // Output: Instructor moves with effort.
Person p2 = new CollegeStudent();
p2.move(); // Output: College student moves quickly.
}
}
Polymorphism requires: inheritance/implementation, a parent class reference holding a subclass object, and method overriding. Note that Java’s member variables (attributes) do not exhibit polymorphism—only objects and behaviors do.
Benefits of polymorphism: The right - side object in polymorphic form is decoupled, enabling easier extension and maintenance. Using a parent class type as a method parameter allows accepting any subclass object, enhancing extensibility.
Final Keyword
The final keyword (meaning "final" or "unchangeable") can modify classes, methods, or variables:
- Class: A
finalclass cannot be inherited. - Method: A
finalmethod cannot be overridden. - Variable: A
finalvariable can only be assigned once.
Constents
A member variable with static final is a constant, used for system configuration:
class Config {
public static final String ORGANIZATION_NAME = "Chuanshu Education";
}
Constant naming: Use uppercase with underscores (e.g., ORGANIZATION_NAME). At compile time, constants are "macro - replaced" (literal values replace references), ensuring optimal performance.
Abstract Class
The abstract keyword modifies classes (abstract classes) or methods (abstract methods, no body):
abstract class AbstractExample {
public abstract void performAction();
}
Abstract methods require subclasses to provide implementations (unless the subclass is also abstract).