-3

Is it necessary to declare default constructor while using parameterized constructor?

We can create parameterized object of that class, and the object can be used to call other function of that class, then why do we need default constructor?

public class Const {
    Const(int s,int  t) {
       int b=s+t;
       System.out.println(b);
    }

    public int add(int a) {
        int j = 9;
        j=j+a;
        return j;
    }
}

public class Construct {
    public static void main(String[] args) {
        Const obj =new Const(5,9);

        obj.add(55);
    }
}

Here we don't need for default constructor. Can we not go with this object?

3 Answers3

0

Your code is perfectly fine. There is no need for the default constructor at all. You can even make all constructors private so that you have no access to any constructors:

public class PrivateClassTest
{
    // Default constructor that is not accessible by others
    private PrivateClassTest()
    {
    }
}
0

Constructor is used to initialize an object. In other words, constructor provide memory to an object. Without initializing an object we can’t use its properties.

But there is no need to define or declare a default constructor in Java. The compiler implicitly add a default constructor in the program if we have not declared or defined it.

-1

We need default constructor when we are implementing inheritance in our project structure.

Example:

Class Apple{
    Apple(){}

    Apple(String a){
       System.out.pritnln(a);
    }
}

Class Banana extends Apple{
    Banana(){}

    public static void main(String[] args){
       Apple("Eaten");
    }
}

In Above Scenario, if you will not declare any default constructor for class Apple then it will throw an error:
Implicit super constructor Apple() is undefined for default constructor. Must define an explicit constructor

Because class Banana will always try to call super constructor which is not parameterized and if you have declared one parameterized constructor then you must need to declare default constructor.

Dushyant Tankariya
  • 1,432
  • 3
  • 11
  • 17
  • That is just plain wrong. `Apple` does not need a default constructor. You would just need to make an explicit super call to the `Apple(String a)` constructor in your `Banana` constructor: Change the Bana constructor to `Banana(){super("Banana");}` and you can delete the Apple default constructor. – OH GOD SPIDERS Jul 02 '19 at 08:51
  • Yes, you're right conceptually but what I'm trying to explain to him is when he needs a default constructor as necessary. – Dushyant Tankariya Jul 02 '19 at 09:01