기본 생성자(인수 없는 생성자)
인수가 없는 생성자는 매개변수를 허용하지 않으며 해당 기본값으로 클래스 변수를 인스턴스화합니다(예:객체의 경우 null, float 및 double의 경우 0.0, Boolean의 경우 false, byte, short, int 및, long의 경우 0).
생성자를 명시적으로 호출할 필요가 없습니다. 생성자는 인스턴스화 시 자동으로 호출됩니다.
기억해야 할 규칙
생성자를 정의하는 동안 다음 사항을 염두에 두어야 합니다.
생성자에는 반환 유형이 없습니다.
생성자의 이름은 클래스의 이름과 동일합니다.
생성자는 추상, 최종, 정적 및 동기화될 수 없습니다.
생성자와 함께 public, protected 및 private 액세스 지정자를 사용할 수 있습니다.
예
class NumberValue {
private int num;
public void display() {
System.out.println("The number is: " + num);
}
}
public class Demo {
public static void main(String[] args) {
NumberValue obj = new NumberValue();
obj.display();
}
} 출력
The number is: 0
예
public class Student {
public final String name;
public final int age;
public Student(){
this.name = "Raju";
this.age = 20;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
new Student().display();
}
} 출력
Name of the Student: Raju Age of the Student: 20