Master Core Java Step-by-Step!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential interview insights!
Subscribe Now on YouTubePassing Arguments to Superclass Constructors
In Java inheritance, subclasses frequently need to pass specific data up to parent class constructors during object creation. While a default constructor takes no values, a parameterized superclass constructor allows you to set up essential parent fields immediately.
To pass arguments up to a parent constructor, Java provides the parameterized syntax: super(argument1, argument2, ...);.
Why Use super() with Parameters?
Calling parameterized constructors in the superclass provides several key advantages:
- Code Reusability: Instead of duplicating initialization code in the child class, the parent constructor handles common setup logic.
- Data Encapsulation: Private parent variables can be safely initialized via the superclass constructor without exposing direct access.
- Explicit Control: It ensures that the parent object state is properly established with valid data right at the moment of instantiation.
Step-by-Step Code Example
class Animal {
String name;
// Parameterized parent constructor
Animal(String name) {
this.name = name;
System.out.println("Animal constructor called for: " + name);
}
}
class Dog extends Animal {
String breed;
Dog(String name, String breed) {
super(name); // Passes the name argument to the parent constructor
this.breed = breed;
System.out.println("Dog breed: " + breed);
}
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog("Buddy", "Labrador");
}
}
Output:
Dog breed: Labrador
Key Rules to Follow
- Must Be the First Line: Just like the default
super()call,super(...)with parameters must always be the very first statement inside the subclass constructor. - Matching Arguments: The argument count, order, and data types passed into
super(...)must exactly match a constructor signature in the superclass. - No Multiple Invocations: You cannot call
super(...)more than once within the same constructor.
No comments:
Post a Comment