What is Default Constructor in Java?
A constructor in Java is a special method that is used to create objects of a class. A default constructor is a special type of constructor that is automatically generated by the Java compiler if no other constructor is defined in a class. This default constructor has no parameters and an empty body.
For example, consider the following class definition:
public class MyClass { // Default constructor public MyClass() { } }
In this example, the default constructor is defined explicitly with an empty body. If this constructor is not defined, the compiler will automatically generate a default constructor for the class using super() keyword, which will look like this:
public class MyClass { // Default constructor generated by the compiler public MyClass() { super(); } }
Write a Java Program to Prove that the Default Constructor of the Super Class is Available to Sub Class by Default.
Whenever a child class constructor is executed it has to call immediate parent class constructor first then itself. If a child class constructor is failed to call immediate parent class constructor first then it cannot run itself. Thus it gives us a proof that Default Constructor of the Super Class is Available to Sub Class by Default.
Here is the source code of the Java Program to Prove that the Default Constructor of the Super Class is Available to Sub Class by Default. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
/*
* Default Constructor Progam in Java
*/
class Sup
{
static int a, b;
Sup()
{
System.out.println("super class default constructor");
}
}
public class Sub extends Sup
{
Sub()
{
System.out.println("sub class default constructor");
}
public static void main(String[] args)
{
new Sub();
}
}
1. This program demonstrates inheritance in Java, where the Sub class inherits the behavior of the Sup class and adds its own behavior.
2. This Java program has two classes, Sup and Sub. Sup has two static variables and a default constructor that prints a message.
3. Sub extends Sup and has a default constructor that prints a different message.
4. In the main method, an instance of Sub is created using the new keyword. This invokes the constructor of Sup, which prints its message, and then the constructor of Sub, which prints its message.
5. Finally, the program terminates.
$ javac Sub.java $ java Sub super class default constructor sub class default constructor
To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.
- Check Programming Books
- Check Java Books
- Practice BCA MCQs
- Practice Information Technology MCQs
- Practice Programming MCQs