- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Demonstrate constructors in a Multilevel Hierarchy in Java
Multilevel inheritance is when a class inherits a class which inherits another class. An example of this is class C inherits class B and class B in turn inherits class A.
A program that demonstrates constructors in a Multilevel Hierarchy in Java is given as follows:
Example
class A { A() { System.out.println("This is constructor of class A"); } } class B extends A { B() { System.out.println("This is constructor of class B"); } } class C extends B { C() { System.out.println("This is constructor of class C"); } } public class Demo { public static void main(String args[]) { C obj = new C(); } }
Output
This is constructor of class A This is constructor of class B This is constructor of class C
Now let us understand the above program.
The class A contains the constructor A(). The class B uses the extends keyword to inherit class A. It also contains the constructor B(). The class C uses the extends keyword to inherit class B. It contains the constructor C(). A code snippet which demonstrates this is as follows:
class A { A() { System.out.println("This is constructor of class A"); } } class B extends A { B() { System.out.println("This is constructor of class B"); } } class C extends B { C() { System.out.println("This is constructor of class C"); } }
In the main() method in class Demo, an object obj of class C is created. A code snippet which demonstrates this is as follows:
public class Demo { public static void main(String args[]) { C obj = new C(); } }
Advertisements
To Continue Learning Please Login
Login with Google