Search⌘ K

Solution Review: Implement the Parametrized Constructor

Explore how to implement parametrized constructors in Java using inheritance. Understand the use of the super keyword to call base class constructors, enabling you to initialize derived class objects properly and write cleaner object-oriented code.

We'll cover the following...

Solution

Java
// Base Class
class Laptop {
// Private Data Members
private String name;
public Laptop() { // Default Constructor
name = "";
}
public Laptop(String name) { // Default Constructor
this.name = name;
}
// Getter Function
public String getName() {
return name;
}
}
// Derived Class
class Dell extends Laptop {
public Dell() { // Default Constructor
}
public Dell(String name) { // Parametrized Constructor
super(name);
}
public String getDetails() {
return getName();
}
public static void main(String args[]) {
Dell dell = new Dell("Dell Inspiron");
System.out.println(dell.getDetails());
}
}

Explanation

...