ADVERTISEMENT
ADVERTISEMENT

Java program to call a superclass constructor from sub/child class

Learn how to call a superclass constructor from sub/child class in Java?
Submitted by Nidhi, on March 23, 2022

Problem Solution:

In this program, we will inherit a class into another class using the "extends" keyword. Then we will call Superclass constructor from child/subclass constructor using the 'super' keyword.

Program/Source Code:

The source code to call a superclass constructor from sub/child class is given below. The given program is compiled and executed successfully.

// Java program to call a superclass constructor 
// from sub/child class

class Super {
  Super() {
    System.out.println("Super class constructor called.");
  }
}

class Sub extends Super {
  Sub() {
    super();
    System.out.println("Sub class constructor called.");
  }
}

public class Main {
  public static void main(String[] args) {
    Sub obj = new Sub();
  }
}

Output:

Super class constructor called.
Sub class constructor called.

Explanation:

In the above program, we created 3 classes Super, Sub, and Main. The Super and Subclass contain a constructor. Here, we inherited the Superclass into Sub class using the "extends" keyword.  In the Sub Class constructor, we accessed the superclass constructor using the super keyword.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the object of Subclass and called both class constructors, and printed the messages.

Java Inheritance Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.