[Java] 자바 생성자 (constructor)와 오버로딩 (overloading)


2017/05/11 - [java] - #Java 스태틱 블록 (static block), 인스턴스 블록 (instance block), 생성자

2017/05/10 - [java] - #Java 생성자(constructor)


overloading (오버로딩)

- 파라미터 타입이 다르거나 개수가 다른 생성자 또는 메서드를  여러 개 중복해서 

  만드는 문법을 말한다.

- 인스턴스를 생성할 때, 넘겨주는 아규먼트의 값과 순서에 따라 호출되는 생성자 메서드가 달라진다.



생성자 오버로딩 예제


static class Student {

    static String name = "홍길동"; // 변수 선언에 값을 초기화시키는 문장을 포함할 수 있다.
   
    int age = 20;
   
    Student() {
      System.out.println("Student()... 호출");
    }
   
    Student(int a) {
      System.out.println("Student(int)... 호출");
      this.age = a;
    }
   
    Student(int a, String n) {
      System.out.println("Student(int, String)... 호출");
      this.age = a;
    }
   
    Student(String n, int a) {
      System.out.println("Student(String, int)... 호출");
      this.age = a;
    }

  }



생성자 호출 코드


public static void main(String[] args) {

    new Student();
    System.out.println("---------------------------");
    new Student("홍길동", 20);
    new Student(20, "홍길동");

  }


- 실행 결과 :

    Student()... 호출

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

    Student(String, int)... 호출

    Student(int, String)... 호출




블로그 이미지

필로그래머

,