JAVA를 잡아라!...

JAVA_class 만들기_#1_생성자 오버로딩_ColorPoint 본문

JAVA/JAVA_복습문제

JAVA_class 만들기_#1_생성자 오버로딩_ColorPoint

onivv 2023. 11. 30. 15:08

Tip ★

- 인자가 가장 많은 생성자부터 작성

- this(키워드) : 내 멤버변수 중에 변수를 불러와줘!, 모든 멤버변수 앞에는 this 붙여주자.

 

문제

ColorPoint 색깔점 클래스가 있습니다.

new ColorPoint(); // 검정(0,0)

new ColorPoint(1,2); // 검정(1,2)

new ColorPoint("분홍"); // 분홍(0,0)

new ColorPoint("빨강",3,5); // 빨강(3,5)

 

색깔점객체명.printInfo();

--> 검정색 점은 (0,0)에 있습니다.

 

코드_ver1

package class01;

class ColorPoint {
	int x;
	int y;
	String color;
	
	ColorPoint(){
		this.color = "검정";
		this.x = 0;
		this.y = 0;
	}
	ColorPoint(int x, int y){
		this.color = "검정";
		this.x = a;
		this.y = b;		
	}
	ColorPoint(String color){
		this.color = color;
		this.x = 0; //heap 영역이라서 초기화가 자동이지만
		this.y = 0; //직접 0을 대입해주는 것이 바람직
	}
	ColorPoint(String color, int x, int y){
		this.color = color;
		this.x = x;
		this.y = y;
	}
	void printInfo() {
		System.out.println(this.color + "색 점은 (" + this.x + "," + this.y + ")에 있습니다.");
	}
}

public class Test03_ColorPoint {

	public static void main(String[] args) {
		
		ColorPoint cp1 = new ColorPoint(); // 검정(0,0)
		ColorPoint cp2 = new ColorPoint(1,2); // 검정(1,2)
		ColorPoint cp3 = new ColorPoint("분홍"); // 분홍(0,0)
		ColorPoint cp4 = new ColorPoint("빨강",3,5); // 빨강(3,5)
		cp1.printInfo();
		cp2.printInfo();
		cp3.printInfo();
		cp4.printInfo();
		
	}
	
}

 

코드_ver2 : 재사용 this()

package class01;

class ColorPoint {
	int x;
	int y;
	String color;
	
	ColorPoint(){
		this("검정",0,0);
		//this(0,0)
		//하드코딩 최소화!!
		//아래 정수인자 2개 받는 생성자에서 이미 "검정"
	}
	ColorPoint(int x, int y){
		this("검정",x,y);	
	}
	ColorPoint(String color){
		this(color,0,0);
	}
	ColorPoint(String color, int x, int y){
		this.color = color;
		this.x = x;
		this.y = y;
	}
	void printInfo() {
		System.out.println(this.color + "색 점은 (" + this.x + "," + this.y + ")에 있습니다.");
	}
	void changeColor(String color) {
		this.s = color;
	}
	void move(int x, int y) {
		this.a+=x;
		this.b+=y;
	}
}

public class Test03_ColorPoint {

	public static void main(String[] args) {
		
		ColorPoint cp1 = new ColorPoint(); // 검정(0,0)
		ColorPoint cp2 = new ColorPoint(1,2); // 검정(1,2)
		ColorPoint cp3 = new ColorPoint("분홍"); // 분홍(0,0)
		ColorPoint cp4 = new ColorPoint("빨강",3,5); // 빨강(3,5)
		cp1.printInfo();
		cp2.printInfo();
		cp3.printInfo();
		cp4.printInfo();
        
		//매개변수에 변화를 주고싶음 (색깔바꾸고,위치바꾸고)
		//코드는 위에서부터 아래로 읽히기 때문에 코드 위치 조심!
		ColorPoint cp = new ColorPoint("분홍",10,10);
		cp.changeColor("핑크");		//인자1개outputX
		cp.move(1, 2);			//인자2개outputX
		cp.printInfo();
		
	}
	
}

 

출력

검정색 점은 (0,0)에 있습니다.
검정색 점은 (1,2)에 있습니다.
분홍색 점은 (0,0)에 있습니다.
빨강색 점은 (3,5)에 있습니다.
핑크색 점은 (11,12)에 있습니다.