Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the no args have to be present for the code to work?

Tags:

java

On this piece of code I understand it works with either super(t) in Class A or a no args constructor in class B. Below the code uses the no args constructor in class B. I understand that if you take the no args constructor out of class B the code does not work. I'm new to programming and what I'm trying to understand is what is so special about the no args constructor in class B, Why does it have to be present for the code to work? What is the special condition or rule?

public class Test {

    public static void main(String[] args) {

       B b = new B(5);

    }
}

class A extends B {
    public A(int t)  {

        System.out.println("A's constructor is invoked");
    }
}

class B  {

    public B() {

    }

    public B(int k)   {
    System.out.println("B's constructor is invoked");
    }
}
like image 787
John W Avatar asked Jan 10 '13 06:01

John W


People also ask

Why do we need no args constructor?

A constructor with or without parameters has a purpose of creating in object in order to access the methods in its class. With the no parameter constructor, you are able to create the object in order to access the methods in its class.

What happens when the no args constructor is absent in the entity bean?

The instance of the entity bean cannot be created when there is no no-arg (default) constructor.

Why do we need no argument constructor in spring boot?

The arguments of a constructor can only be found by type, not by name, so there is no way for the framework to reliably match properties to constructor args. Therefore, they require a no-arg constructor to create the object, then can use the setter methods to initialise the data.

What happens if your class doesn't have a no argument constructor?

In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object , which does have a no-argument constructor. You can use a superclass constructor yourself.


1 Answers

class A extends B {

Compiler ensures while compiling this class; if programmer doesn't write this() or super() explicitely, it will add super() as very first line in every constructor provided in class A.

And compiler also ensures to add no-arg constructor to a class if no other constructor in provided by programmer.

Now, lets say you don't provide no-arg constructor in class B and compiler will also no provide cause you have provided constructor with argument. But, in class A it'll add super() as very first line in constructor. i.e. a call to base class no-arg construtor. Thus, it'll lead to compiler error.

So, as you said, either provide no-arg constructor in class B OR write super(<int>) in class A.

like image 101
Azodious Avatar answered Oct 21 '22 20:10

Azodious