Multilevel Inheritance

Easy
0/40
18 upvotes
Asked in company
SAP Labs

Problem statement

Create a class GrandFather that has a parameterized constructor and a grandFatherName attribute.

Create another class Father that inherits the property of GrandFather and has a parameterized constructor with an additional argument fatherName.

Create another class Son that inherits Father's property and has a parameterized constructor with an additional argument sonName and a printName method that prints the sonName,fatherName, and grandFatherName into the format as shown below in SampleOutput 1.

You need to create the object of Son class and pass the value of sonName,fatherName,grandFatherName as 'Saurabh', 'Ramesh', and 'Suresh' respectively and call the printName method.

Sample Output 1 :
sonname:  Saurabh
fathername:  Ramesh
grandfather:  Suresh
Note:
Keep all the attribute value static as  above mention in sample output 1.
Approaches (1)
Intuitive Approach
  • First, we are creating class Grandfather has an attribute grandfathername after that creating class
  • Father has an additional attribute fathername now further creating a class has all the property of Father and additional attribute sonname.
  • Now when we call our Father class using super by passing attribute fathername and grandfather name then father class set the value of fathername as Ramesh. It calls its parent class Grandfather and grandfather set the value of attribute grandfathername as Suresh. After that, we are calling printName method.
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Multilevel Inheritance
Full screen
Console