×
Java Inheritance Details
Purpose: Allows classes to share fields and methods in a hierarchy, reducing redundancy.
Hierarchy:
Subclasses inherit fields and methods from superclasses.
The Object class is the root of all classes; if no superclass is specified, it defaults to Object.
Java supports single inheritance (a class can extend only one other class).
Class Composition: Subclass instances contain both their own fields and those of the superclass.
Key Methods in Object Class:
clone(): Creates a shallow copy. To ensure a deep copy, classes should implement Cloneable.
equals(): Should be overridden, as the default method uses ==.
toString(): Used by methods like printf; often overridden for more descriptive output.
Constructor Chaining and Rules:
Constructor Chaining: Ensures superclass constructors are called during object creation, using super() in subclasses.
Constructor Rules:
Each class must have a constructor (Java provides a default if none is defined).
The first line in a constructor must call another constructor or the superclass constructor (this() or super()).
If the superclass lacks a parameterless constructor, the subclass must call an existing constructor explicitly.
Subclass Access and Modifiers:
Access Modifiers:
Private fields in a superclass cannot be accessed by subclasses.
Protected allows access within subclasses.
Other modifiers: public, protected, private, and package-private (no modifier).
Accessing Superclass Methods: Overridden methods can call the superclass version using super.methodName().
Overloading vs. Overriding:
Overloading: Same method name in the same class with different parameters.
Overriding: Same method name and parameters in both superclass and subclass, where the subclass version takes precedence.
Use @Override to verify correct overriding.
Special Operators:
instanceof: Used to check if an object is an instance of a specific class or subclass.