
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Call Super in Constructor Without Extending Any Class in Java
A super keyword is a reference of the superclass object in Java. Using this, you can invoke the instance methods constructors and, variables, of a superclass.
Calling the constructor of a superclass
You can call the constructor of a superclass from the subclass’s constructor.
Example
Consider the following example, it has two classes SuperClass class and SubClass where the SubClass extends the SuperClass. The superclass has a parameterized constructor, we are invoking it from the subclass using the "super" keyword.
class SuperClass{ SuperClass(int data){ System.out.println("Superclass's constructor: "+data); } } public class SubClass extends SuperClass{ SubClass(int data) { super(data); } public static void main(String args[]){ SubClass sub = new SubClass(400); } }
Output
Superclass's constructor: 400
If the SuperClass has a default Constructor there is no need to call it using"super()" explicitly, it will be invoked implicitly.
Example
class SuperClass{ SuperClass(){ System.out.println("Superclass's constructor"); } } public class SubClass extends SuperClass{ SubClass() { //super(); } public static void main(String args[]){ SubClass sub = new SubClass(); } }
Output
Superclass's constructor
If we call "super()" without any superclass
Actually, nothing will be displayed. Since the class named Object is the superclass of all classes in Java. If you call "super()" without any superclass, Internally, the default constructor of the Object class will be invoked (which displays nothing).
public class Sample { Sample() { super(); } public static void main(String args[]){ Sample sub = new Sample(); } }
Output
//Nothing will be displayed……