IT박스

자바 기본 생성자

itboxs 2020. 6. 14. 11:13
반응형

자바 기본 생성자


기본 생성자가 정확히 무엇입니까 — 다음 중 하나가 기본 생성자이며 다른 생성자와 다른 점을 알려줄 수 있습니까?

public Module() {
   this.name = "";
   this.credits = 0;
   this.hours = 0;
}

public Module(String name, int credits, int hours) {
   this.name = name;
   this.credits = credits;
   this.hours = hours;
}

둘 다 아닙니다. 정의하면 기본값이 아닙니다.

기본 생성자는 다른 생성자를 정의하지 않으면 인수가없는 생성자가 자동으로 생성됩니다. 초기화되지 않은 필드는 기본값으로 설정됩니다. 예를 들어 유형이 String, intint클래스 자체가 공개 라고 가정하면 다음과 같습니다 .

public Module()
{
  super();
  this.name = null;
  this.credits = 0;
  this.hours = 0;
}

이것은 정확히 동일

public Module()
{}

그리고 생성자가 전혀없는 것과 똑같습니다. 그러나 하나 이상의 생성자를 정의하면 기본 생성자가 생성되지 않습니다.

참조 : Java 언어 사양

클래스에 생성자 선언이없는 경우 공식 매개 변수가없고 throws 절이없는 기본 생성자가 암시 적으로 선언됩니다.

설명

기술적으로 필드를 기본값으로 초기화하는 생성자 (기본값 또는 다른 방법)가 아닙니다. 그러나 나는 대답을 남겨두고 있기 때문에

  • 질문은 기본값이 잘못되었습니다.
  • 생성자는 포함 여부에 관계없이 동일한 효과를 갖습니다.

클래스에 생성자를 정의하지 않으면 기본 생성자가 생성됩니다. 그것은 아무 것도하지 않는 인수없는 생성자입니다. 편집 : super () 호출 제외

public Module(){
}

클래스에서 하나 이상의 생성자를 명시 적으로 정의하지 않으면 컴파일러에서 기본 생성자를 자동으로 생성합니다. 두 개를 정의 했으므로 클래스에 기본 생성자가 없습니다.

Java 언어 스펙 제 3 판 :

8.8.9 기본 생성자

클래스에 생성자 선언이 없으면 매개 변수를 사용하지 않는 기본 생성자가 자동으로 제공됩니다.


안녕. 내 지식에 따라 기본 생성자의 개념을 명확히하겠습니다.

컴파일러는 생성자가없는 모든 클래스에 대해 인수없는 기본 생성자를 자동으로 제공합니다. 이 기본 생성자는 수퍼 클래스의 인수가없는 생성자를 호출합니다. 이 상황에서 수퍼 클래스에 인수가없는 생성자가없는 경우 컴파일러에서 불만을 표시하므로이를 검증해야합니다. 클래스에 명시적인 슈퍼 클래스가없는 경우, 인수가없는 생성자가있는 Object의 암시 적 슈퍼 클래스가 있습니다.

Java Tutorials 에서이 정보를 읽었습니다 .


Java는 명시적인 생성자가 제공되지 않을 때 인수를 사용하지 않고 특별한 조치 나 초기화를 수행하지 않는 기본 생성자를 제공합니다.

암시 적 기본 생성자가 취하는 유일한 조치는 super () 호출을 사용하여 수퍼 클래스 생성자를 호출하는 것입니다. 생성자 인수는 객체의 초기화를위한 매개 변수를 제공하는 방법을 제공합니다.

아래는 2 개의 생성자를 포함하는 큐브 클래스의 예입니다. (하나의 기본값과 하나의 매개 변수화 된 생성자).

public class Cube1 {
    int length;
    int breadth;
    int height;
    public int getVolume() {
        return (length * breadth * height);
    }

    Cube1() {
        length = 10;
        breadth = 10;
        height = 10;
    }

    Cube1(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
    }

    public static void main(String[] args) {
        Cube1 cubeObj1, cubeObj2;
        cubeObj1 = new Cube1();
        cubeObj2 = new Cube1(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
        System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
    }
}

일반적인 용어는 객체에 생성자를 제공하지 않으면 기본 생성자라는 인수 생성자가 자동으로 배치되지 않는다는 것입니다.

If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.

As per the docs

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

Example

public class Dog
{
}

will automatically be modified(by adding default constructor) as follows

public class Dog{
    public Dog() {

    }
} 

and when you create it's object

 Dog myDog = new Dog();

this default constructor is invoked.


default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.

If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super(), has no throws clause as well no formal parameters.

E.g.

class Klass {
      // Default Constructor gets generated
} 

new Klass();  // Correct
-------------------------------------

class KlassParameterized {

    KlassParameterized ( String str ) {   //// Parameterized Constructor
        // do Something
    }
} 

new KlassParameterized(); //// Wrong  - you need to explicitly provide no-arg constructor. The compiler now never declares default one.


--------------------------------

class KlassCorrected {

    KlassCorrected (){    // No-arg Constructor
       /// Safe to Invoke
    }
    KlassCorrected ( String str ) {   //// Parameterized Constructor
        // do Something
    }
} 

new KlassCorrected();    /// RIGHT  -- you can instantiate

If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.

In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.

public Module()
{
   super();
}

Note: In side default constructor, it will add super() call also, to call super class constructor.

Purpose of adding default constructor:

Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.

That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.


When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.

The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.

Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.


A default constructor does not take any arguments:

public class Student { 
    // default constructor
    public Student() {   

    }
}

I hope you got your answer regarding which is default constructor. But I am giving below statements to correct the comments given.

  • Java does not initialize any local variable to any default value. So if you are creating an Object of a class it will call default constructor and provide default values to Object.

  • Default constructor provides the default values to the object like 0, null etc. depending on the type.

Please refer below link for more details.

https://www.javatpoint.com/constructor

참고URL : https://stackoverflow.com/questions/4488716/java-default-constructor

반응형