본문 바로가기

KOSTA 수업 내용 정리

2주차 Day3(생성자, 인스턴스 객체, super()사용, this() 사용)

1. Circle 인스턴스 객체를 사용하려면

1) 변수 선언(circle1)

2)new Circle(여기)  ( ) 내부의 타입을, Circle클래스에 생성자로 설정해줘야 사용 가능

public class ShapeMain {

  public static void main(String[] args) {

    Circle circle1 = new Circle("빨강", new Point(10,20), 5); // 색, 중심점, 반지름
    Circle circle2 = new Circle("주황", 35, 24, 15); // 색, 중심점x, 중심점y, 반지름

    Rectangle rectangle1 = new Rectangle("파랑", new Point(3, 5), 20, 10); //색, 시작점, 가로, 세로
    Rectangle rectangle2 = new Rectangle("하늘", 50, 60, 10, 20); //색, 시작점, 가로, 세로

    Triangle triangle1 = new Triangle("초록", new Point(10,1), new Point(1,20), new Point(10,20));
    Triangle triangle2 = new Triangle("연두", 10,1,1,20,10,20);

  }
};

 

3) circle1에 해당하는 생성자 생성

4) 여기서 Circle의 매개변수인 color는 부모 클래스인 Shape에서 가져온다

5) 매개변수에는 String color라고 써줘야 하고, 생성자 내부에 super(color);이런식으로 설정해서 사용 가능.

public class Circle extends Shape {

  Point center;
  int radius;
  int z;

//circle1에 해당하는 생성자 및 타입
  Circle(String color, Point center, int radius) {
    super(color);
    this.center = center;
    this.radius = radius;
  }
  Circle(String color, int x, int y, int radius) {
    super(color);
    this.center = new Point(x, y);
    this.radius = radius;
  }

 

 

 

** this()의 사용

1) circle2의 this(color, new ...) 부분은

   바로위 Circle1의 생성자를 가져와서 사용한다는 말.

2)보통 this는 해당 클래스 내부의 인스턴스 객체를 가리키는데,

    circle1과 같이 생성자의 매개변수의 타입이 같다면, this( )를 통해서 사용할 수 있다.

public class Triangle extends Shape {
  Point pos1;
  Point pos2;
  Point pos3;

  //circle1
  public Triangle(String color, Point pos1, Point pos2, Point pos3) {
    super(color);
    this.pos1 = pos1;
    this.pos2 = pos2;
    this.pos3 = pos3;
  }

  //circle2
  public Triangle(String color, int px1, int py1, int px2, int py2, int px3, int py3) {
    this(color, new Point(px1, py1), new Point(px2, py2), new Point(px3, py3));
  }