Computer Science/자료구조

[Java로 배우는 자료구조] 제2-2장: 메서드와 생성자 (2/3)

문에딕트 2022. 3. 7. 15:56

생성자

  • 클래스의 특별한 함수 멤버(메서드)
  • 클래스와 동일한 이름
  • 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()){
                int x = in.nextInt();
                int y = in.nextInt();
                int w = in.nextInt();
                int h = in.nextInt();

                rects[n] = new MyRectangle2( x, y, w, h);

                //축약 버전
                //rects[n] = new MyRectangle2(in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt() );
                n++;
            }


            in.close();
        } catch (FileNotFoundException e) {
            System.out.println("No data file.");
            System.exit(1);
            e.printStackTrace();
        }

        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].calcArea() > rects[j+1].calcArea()){
                    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 MyRectangle2( MyPoint2 p, int  w, int h){
        lu = p;
     
        width = w;
        height = h;
    }

    public int calcArea()  // code09에서 이 메서드를 가져와 파라미터의 MyRectangle2 r는 자기자신이기 때문에 지워준다
    {
        return width * height;
    } 

    public String toString(){  // toString 메소드는 특별
        return "("+ lu.x + ", " + lu.y +") " + width + " " + height;
    }

    
}