014-003-009
Constructor Call with super
Easy
Problem Description
Constructor Call with super
In this problem: You will create an Animal class and a Dog class, where Dog's constructor explicitly calls the parent class constructor using super().
Learning Objective: Understand the mechanism of explicitly calling a parent class constructor using the super() keyword in inheritance
Overview
In a subclass constructor, you can explicitly call the parent class constructor using super(). This allows delegating the initialization of fields defined in the parent class to the parent class itself.
Specifications
Animal Class
- Has
String nameandint agefields - Constructor
Animal(String name, int age)initializes both fields showInfo()method outputs"Name: <name>, Age: <age>"
Dog Class (extends Animal)
- Adds a
String breedfield - Constructor
Dog(String name, int age, String breed)callssuper(name, age)and initializesbreed - Overrides
showInfo()to callsuper.showInfo()then output"Breed: <breed>"
Main Class
- Creates a
Dogobject withnew Dog("Pochi", 3, "Shiba") - Calls
showInfo()
Output Format
Name: Pochi, Age: 3
Breed: Shiba
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up