Friday 26 May 2023

Inheritance and Constructors in Java: is constructor inherited in Java?

Understanding how the constructors work within the inheritance idea is crucial. The constructors are never passed down to any child classes during inheritance.

In Java, a parent class's default constructor is automatically called by the constructor of its child class. That implies that the parent class constructor is called first, followed by the child class constructor, when we create an object of the child class.

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

class B extends A
{
    B()
    {
       System.out.println("\n Sub class constructor");
    }
}

class Demo
{
    public static void main(String args[])
    {
        B obj1 =new B();
        
    }
}

 Output:

 Super class constructor

 Sub class constructor

However, only the default constructor will be automatically invoked by the child class constructor if the parent class contains both a default and a parameterized constructor.

The parametrized constructor of the super class is called using super keyword. The point to note is base class constructor call must be the first line in the derived class constructor.

class A {
    int x;
    A(int x)
    {
        System.out.println("Super class constructor");
        System.out.println(x);
    }
    
}

class B extends A
{
    B(int x)
    {  super(x);
       System.out.println("\n Sub class constructor");
       System.out.println(x);
    }
}

class Demo
{
    public static void main(String args[])
    {
        B obj1 =new B(10);
        
    }
}

Output:

Super class constructor
10

 Sub class constructor
10

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top