메서드 오버로딩, 생성자

Dec 25, 2023
메서드 오버로딩, 생성자

1. 메서드 오버로딩(Method overloading)

💡
중복정의. 같은 이름의 메서드가 여러개 존재할 수 있는 것
 
public class Math { int add(int x, int y) { return x + y; } int add(int x, int y, int z) { return x + y + z; } int add(int x, int y, int z, int w) { return x + y + z + w; }
 
같은 이름의 메서드가 있다. 이름은 동일하지만 매개변수의 수가 다르기 때문에 자동으로 구별된다.
 

2. 생성자(Constructor)

💡
객체가 생성될 때 객체를 초기화 하는 것. 생산자의 이름은 클래스와 같다.
 
class people2 { String name = "홍길동"; int age = 20; int weight = 70;
 
이렇게 객체에 값을 입력하게 되면 값의 변화없이 동일한 값이 출력되게 된다.
 
때문에 생성자가 필요하며, 생성자를 만들면 객체가 만들어진 이후에 값을 입력할 수 있다.
 
class people2 { private String name; private int age; private int weight; public people2(String name, int age, int weight) { this.name = name ; this.age = age ; this.weight weight ; }
각 변수 앞에 private 를 붙인 이유는 다른 클래스에서 접근해서 값을 바꿀 수 없고, 메서드를 통해서만 변경하기 위함이다.
 
💡
Alt + Insert 를 누르고 Constructor 를 입력하면 쉽게 생산자를 만들 수 있다.
notion image
public People2(String name, int age, int weight) { this.name = name; this.age = age; this.weight = weight; }
 
3개의 매개변수를 받는 생성자가 만들어졌다. 각 변수 앞에 this 가 포함되어 있는 이유는
매개변수와의 이름이 같을 때 구분을 위해 표시된다.
 
 
class People2 { String name; int age; int weight; public People2(String name, int age, int weight) { this.name = name; this.age = age; this.weight = weight; } void Diet() { this.weight = weight - 10; } void Aging() { this.age++; } @Override public String toString() { return "People2{" + "name='" + name + '\'' + ", age=" + age + ", weight=" + weight + '}'; } } public class ExerciseEx01 { public static void main(String[] args) { People2 p2 = new People2("홍길동", 20, 80); System.out.println(p2); p2.Diet(); p2.Aging(); System.out.println(p2); } }
notion image
 
생성자를 만들면 매개변수를 통해 값을 받을 수 있고, 메서드를 통해 값을 변경할 수 있다.
 
💡
생산자가 선언되어 있다면 기본 생산자를 추가하지 않는다. 즉 People2 p2 = new People2(); 매개변수 값을 비우면 오류가 난다.
notion image
Share article
RSSPowered by inblog