본문 바로가기
[study]이론정리/JAVA(eclipse)

java 6일차 _01. 생성자(2)

by yoon9i 2024. 3. 15.

2. 지정자(modifier)

1) 접근지정자 ( access modifier )
==> 순서중요
       public
       protected
       (default; 지정자가 없으면 기본값.)
       private

==> 접근지정자 사용가능한 경우
        - 클래스
        - 메서드
        - 로컬변수를 제외한 인스턴스 변수 및 클래스변수에 사용 가능.
        - 생성자

- public : 제한이없음
- private : 외부클래스에서는 접근이 불가능. 내부(자신)에서는 접근가능.

2) 일반지정자 ( standard modifier )

- static
- final
- abstract
- transient, ...

3. this 키워드
1) 개념: heap 메모리에 올라간 인스턴스 자신의 주소를 참조한다.
           this 는 생략할 수있다.

2) 반드시 명시적으로 this 를 지정해야 되는 경우가 있음.
==> 인스턴스변수명과 메서드 및 생성자의 파라미터변수명이
       동일한 경우이다.
       문법: this.변수, this.메서드( ); ( 클래스의 멤버를 호출할때 )

ex)
public class Cat {
   
    String name; // 인스턴스 변수
    
    public Cat( String name ) { // 로컬변수(파라미터)
        this.name = name;
                 }
}

==> 생성자에서 다른 생성자를 호출할 때
        문법: this( [값, 값2, ...] );
        ex) this( ); -> Cat( ) 호출 : 기본생성자 호출
this( "야옹이", 2 ); -> Cat5(String name, int age) 호출
this( "야옹이", 2, "암컷" ); 
-> Cat5(String name, int age, String gender) 호출
       
        주의: 반드시 생성자 첫라인에서 지정해야 된다.

ex) 
public Cat5(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}

public Cat5(String name, int age) {
this( name, age, "암컷" );
}

 

package exam09_클래스2_생성자4;

public class Cat4 {
	
	String name;
	int age;
	String gender;
	
	// 오버로딩 생성자
	public Cat4() {
		
	}
	
	public Cat4(String n, int n2, String n3) {
		System.out.println(this);
		this.name = n;
		this.age = n2;
		this.gender = n3;
	}
	
	public Cat4(String n, int n2) {
		name = n; // this 생략
		age = n2; // this 생략
	}
	
	public Cat4(String n) {
		name = n; // this 생략
	}
	
}
package exam09_클래스2_생성자4;

public class TestCat4 {
		
	public static void main(String[] args) {
		
		// 1번 고양이 정보: 야옹이, 2살, 암컷
		Cat4 c1 = new Cat4("야옹이", 2, "암컷");
		
		System.out.println(c1);
		/*
		 * >>> 결과값
		   exam09_클래스2_생성자4.Cat4@73a28541 (주소값)
           exam09_클래스2_생성자4.Cat4@73a28541
		 */
		
		// 2번 고양이 정보 : 망치, 1살, ?
		Cat4 c2 = new Cat4("망치", 1);
		
		// 3번 고양이 정보 : 나비, ?, ?
		Cat4 c3 = new Cat4("나비");
	}
}

 

################################################################################################

 

package exam09_클래스2_생성자5;

public class Cat5 {
	
	String name; // 인스턴스 변수
	int age;
	String gender;
	
	// 이클립스에 의한 생성자 작성( 우클릭 > source > Generate Constructor >
	// superclass: 기본생성자 / fields: 파라미터포함)
	
	public Cat5() {
		// TODO Auto-generated constructor stub
	}
	
	public Cat5(String name, int age, String gender) {
		this.name = name;
		this.age = age;
		this.gender = gender;
	}
	
	public Cat5(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public Cat5(String name) {
		this.name = name;
	}
	
	
	
	
}
package exam09_클래스2_생성자5;

public class TestCat5 {
		
	public static void main(String[] args) {
		
		// 1번 고양이 정보: 야옹이, 2살, 암컷
		Cat5 c1 = new Cat5("야옹이", 2, "암컷");
		
		System.out.println(c1);
		/*
		 * >>> 결과값
		   exam09_클래스2_생성자4.Cat4@73a28541 (주소값)
           exam09_클래스2_생성자4.Cat4@73a28541
		 */
		
		// 2번 고양이 정보 : 망치, 1살, ?
		Cat5 c2 = new Cat5("망치", 1);
		
		// 3번 고양이 정보 : 나비, ?, ?
		Cat5 c3 = new Cat5("나비");
	}
}

 

################################################################################################

package exam09_클래스3_this;

public class Cat6 {
	
	String name; // 인스턴스 변수
	int age;
	String gender;
	
	// 오버로딩 생성자
	public Cat6() {
		
	}
	
	public Cat6(String name, int age, String gender) { // 로컬변수
		System.out.println(this);
		this.name = name;
		this.age = age;
		this.gender = gender;
	}
	
	public Cat6(String n, int n2) {
		name = n; // this 생략
		age = n2; // this 생략
	}
	
	public Cat6(String n) {
		name = n; // this 생략
	}
	
}
package exam09_클래스3_this;

public class TestCat6 {
		
	public static void main(String[] args) {
		
		// 1번 고양이 정보: 야옹이, 2살, 암컷
		Cat6 c1 = new Cat6("야옹이", 2, "암컷");
		
		System.out.println(c1);
		/*
		 * >>> 결과값
		   exam09_클래스2_생성자4.Cat4@73a28541 (주소값)
           exam09_클래스2_생성자4.Cat4@73a28541
		 */
		
		// 2번 고양이 정보 : 망치, 1살, ?
		Cat6 c2 = new Cat6("망치", 1);
		
		// 3번 고양이 정보 : 나비, ?, ?
		Cat6 c3 = new Cat6("나비");
	}
}

 

################################################################################################

package exam09_클래스3_this2;

public class Cat7 {
	
	String name; // 인스턴스 변수
	int age;
	String gender;
	
	// 오버로딩 생성자
	public Cat7() {
		// 기본생성자
	}
	
	public Cat7(String name, int age, String gender) { // 로컬변수
		// 파라미터 3개
//		System.out.println(this);
		System.out.println("생성자");
		this.name = name;
		this.age = age;
		this.gender = gender;
	}
	
	public Cat7(String name, int age) {
		// 파라미터 2개
		this(name, age, "암컷");
	}
	
}
package exam09_클래스3_this2;

public class TestCat7 {
		
	public static void main(String[] args) {
		
		// 변수로 관리
		// 1번 고양이 정보: 야옹이, 2살, 암컷
		Cat7 c1 = new Cat7("야옹이1", 1);
		Cat7 c2 = new Cat7("야옹이2", 5);
		Cat7 c3 = new Cat7("야옹이3", 3);
		Cat7 c4 = new Cat7("야옹이4", 4);
		Cat7 c5 = new Cat7("야옹이5", 2);
		
		Cat7 c100 = new Cat7("야옹이5", 2, "수컷");
		
		System.out.printf("이름: %s, 나이: %d, 성별: %s \n", 
				c1.name, c1.age, c1.gender);
		System.out.printf("이름: %s, 나이: %d, 성별: %s \n", 
				c2.name, c2.age, c2.gender);
		System.out.printf("이름: %s, 나이: %d, 성별: %s \n", 
				c3.name, c3.age, c3.gender);
		System.out.printf("이름: %s, 나이: %d, 성별: %s \n", 
				c4.name, c4.age, c4.gender);
		System.out.printf("이름: %s, 나이: %d, 성별: %s \n", 
				c5.name, c5.age, c5.gender);
		System.out.printf("이름: %s, 나이: %d, 성별: %s \n", 
				c100.name, c100.age, c100.gender);
	}
}

 

Q. 일일이 다 출력을 해야할까?

package exam09_클래스3_this2;

public class TestCat7_배열 {
		
	public static void main(String[] args) {
	
		// 배열로 관리
		
		// 1. Cat 배열 선언
		Cat7 [] cats;
		
		// 2. 배열 생성
		cats = new Cat7[6];
		
		// 3. 배열 초기화
		cats[0] = new Cat7("야옹이1", 1);
		
		Cat7 c2 = new Cat7("야옹이2", 5); // 이 방식도 가능하지만 권장x
		cats[1] = c2;
		
		cats[2] = new Cat7("야옹이3", 3);
		cats[3] = new Cat7("야옹이4", 4);
		cats[4] = new Cat7("야옹이5", 2);
		cats[5] = new Cat7("야옹이100", 2, "수컷");
		
		// 일반 for 문
		System.out.println();
		for (int idx = 0; idx < cats.length; idx++) {
			Cat7 c1 = cats[idx];
			System.out.printf("이름: %s, 나이: %d, 성별: %s \n", 
					c1.name, c1.age, c1.gender);
		}
		
		// foreach 문
		System.out.println();
		for (Cat7 c1 : cats) {
			System.out.printf("이름: %s, 나이: %d, 성별: %s \n", 
					c1.name, c1.age, c1.gender);
		}
		
	}
}

 

배열로 관리를 하게 되면 더 편하게 관리할수있다.

 

생성자와 this 를 좀더 쉽게 설명한 이미지이다.