logo

Java에서 생성자를 사용하는 이유는 무엇입니까?

이 섹션에서는 다음 내용을 학습합니다. Java에서 생성자를 사용하는 이유 그리고 목적은 무엇입니까 그리고 생성자의 필요 . 이와 함께, 우리는 또한 볼 것입니다 생성자의 유형.

자바에서는 건설자 방식과 비슷합니다. 생성자의 속성은 클래스 이름과 동일한 이름을 가져야 한다는 것입니다. 반환 유형이 없습니다. 생성자를 수동으로 호출할 필요는 없습니다. 인스턴스화 중에 암시적으로 자동으로 호출됩니다.

즉, 생성자는 객체 생성 중에 new 연산자를 사용하여 런타임에 호출되는 메서드입니다. JVM은 객체를 생성할 때 이를 자동으로 호출합니다. 클래스에 생성자를 정의하지 않으면 기본 생성자는 항상 클래스에 보이지 않게 존재합니다. 생성자를 사용하는 이유는 다음과 같습니다.

  • 생성자를 사용하여 기본 또는 초기 상태로 객체를 초기화합니다. 기본 요소의 기본값은 원하는 값이 아닐 수도 있습니다.
  • 생성자를 사용하는 또 다른 이유는 종속성에 대해 알려주기 때문입니다. 즉, 생성자를 사용하여 해당 클래스의 사용자에게 필요한 종속성을 요청할 수 있습니다.
  • 생성자를 살펴보면 이 클래스를 사용하기 위해 필요한 것이 무엇인지 알 수 있습니다.

즉, 생성자를 사용하여 클래스의 인스턴스 변수를 초기화합니다.

생성자의 유형

Java에는 두 가지 유형의 생성자가 있습니다.

  • 매개변수화된 생성자
  • 기본 생성자

매개변수화된 생성자

이름에서 알 수 있듯이 인수(매개변수)를 허용합니다. 인스턴스화 시 지정된 값으로 인스턴스 변수를 동적으로 초기화하려는 경우 매개변수화된 생성자가 사용됩니다.

 public class Demo { int i; //parameterized constructor public demo(int i) { this.i = i; } } 

기본 생성자

기본 생성자는 어떤 매개변수도 허용하지 않습니다. 특정 값으로 인스턴스 변수를 초기화하려는 경우에 사용됩니다. 모든 Java 클래스에는 눈에 보이지 않는 기본 생성자가 있습니다. 따라서 별도로 정의할 필요는 없습니다. 매개변수화된 생성자를 만들면 기본 생성자가 클래스에서 제거된다는 점을 기억하세요.

 public class Demo { int i; //default constructor public demo() { //the value of i is fixed this.i = 100; } } 

참고: Java 프로그램에 생성자를 제공하지 않으면 Java 컴파일러는 프로그래머를 대신하여 기본 생성자를 작성하고 프로그램을 컴파일합니다. 인스턴스 변수를 기본값으로 초기화합니다. 예를 들어 정수의 경우 0, 부동 소수점의 경우 0.0, 문자열의 경우 null입니다.

프로그램을 만들고 매개변수화된 기본 생성자를 사용해 보겠습니다.

Employee 클래스에서는 두 개의 생성자를 만들었습니다. 하나는 기본 생성자이고 다른 하나는 매개변수화된 생성자입니다. Employee 클래스에는 이름과 나이라는 두 개의 개인 변수가 있습니다. 기본 메소드에서는 클래스를 인스턴스화하고 두 생성자를 모두 사용했습니다.

Employee.java

 import java.util.Scanner; public class Employee { private String name; private int age; //parameterized constructor public Employee(String name, int age) { this.name =name; this.age = age; } //Default constructor public Employee() { this.name = 'William'; this.age = 28; } //method for printing the values public void show() { System.out.println('Name of the employee: '+this.name); System.out.println('Age of the employee: '+this.age); } //main method public static void main(String args[]) { Employee e=new Employee(); //Reading values from user Scanner sc = new Scanner(System.in); System.out.println('Enter the name of the employee: '); String name = sc.nextLine(); System.out.println('Enter the age of the employee: '); int age = sc.nextInt(); System.out.println(' '); //Calling the parameterized constructor System.out.println('Show() method for the parameterized constructor: '); new Employee(name, age).show(); //Calling the default constructor System.out.println('Show() method for the default constructor: '); new Employee().show(); } } 

산출:

 Enter the name of the employee: David Enter the age of the employee: 27 Show() method for the parameterized constructor: Name of the employee: David Age of the employee: 27 Show() method for the default constructor: Name of the employee: William Age of the employee: 28