Is the default constuctor declaration mandatory?

We all know that the JVM provides us with a standard constructor in every java program.

But if we declare any other type of constructor, then it does not provide a default constructor of any type.

So my question is, is it mandatory to declare a default constructor when we declare some other type of constructor in our program.

If YES, then explain why? If NO, also explain why?

Give a solution with a suitable example.

+4
source share
7 answers

, .
, .
, , .

: -

class Base
{
    public Base(int x){
        //some statements
    }
    /*
       some methods
    */
}

class Derived
{
    // only one of the following will be used
    public Derived(){  // This will cause a compile-time error
      //some statements
    }
    public Derived(){  // This will work fine
     //some statements
        super(x);
    }
    /*
      some methods
    */
}

, , , super() . , super() .

0

, . , , . , , - java.awt.Color.

+1

- .

, , , -

,

public class ClassA {

String name;
ClassA(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

, ,

ClassA obj = new ClassA();

, .

ClassA obj = new ClassA("name");

, .

, ,

ClassA() {}

.

+1

, .

class Dog {

Dog(String name)
{
 system.out.println("Dog :" + name);
}
public static void main(String[] args)
{
 Dog d = new Dog("dollar"); // works fine
 Dog d2 = new Dog() // error , no default constructor defined for Dog
}
}
+1

, , , - .

, .

, , ?

, . , : JLS

8.8.9.

, , .

, . .

, , (§6.6), .

+1

, ! , ( ),

A ref = new A();

, , .

0

, .

,                 , , .

         If you create an or many parameterized constructor in java then you do need need to be worried for the default constructor. 

Basically, the constructor is used to initialize instance variables or class members or to perform preliminary tasks, and if you have already done this with another constructor, then there is no need for another, but you can do it if you want.

public class base {int a;

public base(int x)
{
    this.a=x;
    System.out.println(x);
}
public base()
{
    System.out.println("abc");
}

public static void main(String []a)
{
    base b=new base();
    b=new base(4);
}

}

Output: -

a 4

0
source

Source: https://habr.com/ru/post/1532425/


All Articles