생성자

 

클래스 안에 그 클래스와 동일한 이름을 가지며 return 타입이 없는 특별한 메서드를 둘 수 있는데

이것을 생성자 라고 부른다.

 

생성자는 new 명령으로 객체가 생성될때 자동으로 실행된다. 주 목적은 객체의 데이터

필드의 값을 초기화하는 것이다.

 

생성자가 반드시 매개변수를 받아야하는 것은 아니다.

 

package section2;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code09 {

	static MyRectangle2[] rects = new MyRectangle2[100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		try {
			Scanner in = new Scanner(new File("data.txt"));
			
			while(in.hasNext()) {
			rects[n++] = new MyRectangle2(in.nextInt(),in.nextInt(),in.nextInt(),in.nextInt());
			}
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("no data file");
			System.exit(1);
		}
		bubbleSort();
	
		for(int i =0;i<n;i++) 
			System.out.println(rects[i].toString());
		}
	
		private static void bubbleSort() {
			for(int i = n-1;i>0;i--) {
				for(int j =0; j<i; j++) {
					if(rects[j].calArea() > rects[j+1].calArea()) {
						MyRectangle2 tmp = rects[j];
						rects[j] = rects[j+1];
						rects[j+1] = tmp;
					}
				}
			}
		}
}


 

package section2;

public class Mypoint2 {
	public int x;
	public int y;
	
	public Mypoint2(int x, int y) {
		this.x = x;
		this.y = y;
	}
}
package section2;

public class MyRectangle2 {
	public Mypoint2 lu;
	public int width;
	public int height;
	
	public MyRectangle2(int x, int y, int w, int h) {
		lu = new Mypoint2(x,y);
		width =w;
		height = h;
	}
	public int calArea() {
		return width * height;
	}
	
	public String toString() {
		return "("+lu.x + ","+ lu.y +")"+ width + " " + height;
	}
}

생성자를 이용해서 저번 code5를 수정해보았다.

 

어떤 이유때문에 사각형 하나를 표현할때 꼭지점의 좌표와 높이 너비를 이용해 표현하지 않고

대각 방향에 두 꼭지점의 좌표를 이용한다고 했을때

수정이 필요하다!

 

이전 코드였다면 표현방법을 바꿧을뿐인데

그 클래스와 다른클래스 까지 다 바꿔야만 한다.

 

지금은 해당 클래스만 바꾸면 되지만 

메인함수 클래스에서는 대부분 어떠한 것도 바꿀 필요가 없게된다!!

 

어찌되었건 코드의 수정이 적어진다!

응집도를 높이고 결합도가 높아지게 하기 위함이다

 

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

static 그리고 public 1  (0) 2021.06.28
메서드와 생성자 3  (0) 2021.06.24
메서드와 생성자 1  (0) 2021.06.23
클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 4  (0) 2021.06.22

+ Recent posts