In Java inheritance, the super class (parent class) is a general class that defines the behavior and properties of the object, while the subclass (derived class) inherits from the super class and extends its functionality . Subclasses can use non-private members of the superclass and can override superclass methods.
Polymorphism:
Polymorphism allows the behavior of an object to vary depending on its actual type. In Java, a subclass object can be assigned to a superclass object and when a superclass method is called, the actual method executed depends on the actual type of the object.
Advantages of polymorphism:
The challenge of polymorphism:
Best Practices:
Common misunderstandings:
Example:
Consider the following example:
class Shape { protected String name; public void draw() { System.out.println("Drawing a shape"); } } class Rectangle extends Shape { public void draw() { super.draw(); System.out.println("Drawing a rectangle"); } } class Circle extends Shape { public void draw() { super.draw(); System.out.println("Drawing a circle"); } } public class Main { public static void main(String[] args) { Shape s1 = new Rectangle(); Shape s2 = new Circle(); s1.draw(); // Prints "Drawing a rectangle" s2.draw(); // Prints "Drawing a circle" } }
In this example, Shape is the superclass that defines common behavior and properties. Rectangle and Circle are subclasses inherited from Shape that extend the behavior of Shape. The main method creates two Shape objects, one assigned to the Rectangle and the other to the Circle. When the draw() method is called, the actual method executed depends on the actual type of the object, demonstrating polymorphism.
The above is the detailed content of The Maze of Java Inheritance: Navigating Superclasses, Subclasses, and Polymorphism. For more information, please follow other related articles on the PHP Chinese website!