티스토리 뷰

Java

클래스 상속, 포함

Alledy 2019. 5. 7. 17:56

클래스 간의 관계

  • 상속(Inheritance)

    class Parent { } 
    class Child extends Parent { }
    

 

  • 포함(Composite)

    class Circle {
        int x; // 원점 x좌표
        int y; // 원점 y좌표
        int r;
    }
    
    class Point {
        int x;
        int y;
    }
    
    // Point 클래스를 재사용하여 클래스 내에 포함시키는 경우
    class Circle {
        Point c = new Point(); // 원점
        int r; 
    }
    

     

  • 클래스 간 관계 중 어느 것이 적절할 지 판단하는 기준

    상속관계 => ~은 ~이다. (eg. 스포츠카는 자동차이다.)
    포함관계 => ~은 ~을 가지고 있다. (eg. 원은 원점을 가지고 있다.)
    

 

  • 상속 및 포함 예시

    class DrawShape {
        public static void main(String[] args) {
            Point[] p = {
                new Point(100,100),
                new Point(140,50),
                new Point(200,100)
            };
            Triangle t = new Triangle(p); // 배열 p를 넣어 인스턴스 t 초기화 
            Circle c = new Circle(new Point(150, 150), 50); // Point center를 constructor로 초기화해서 Circle 인스턴스 c 초기화에 사용. 
            
            t.draw(); 
            c.draw(); 
        }
    }
    
    class Shape {
        String color = "black";
        void draw() {
            System.out.printf("[color=%s]%n", color);
        }
    }
    
    class Point {
        int x;
        int y;
        
        // constructor
        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
      	Point() {
            this(0,0);
        }
        // 원점 값을 스트링으로 반환
        String getXY() {
            return "(" + x + "," + y + ")";
    	}
    }
    
    class Circle extends Shape { // Shape를 상속 
        Point center; // Point class의 인스턴스 선언
        int r;
        
        Circle() {
            this(new Point(0,0), 100);
        }
        
        // constructor
        Circle(Point center, int r) {
            this.center = center; 
            this.r = r; 
        }
       
        void draw() {
            System.out.printf("[center=(%d,%d), r=%d, color=%s]", center.x, center.y, r, color); // color라는 멤버를 상속받아 가지고 있다. 
        }
    }
    
    class Triangle extends Shape { // Shape 상속
        Point[] p = new Point[3]; // Point 인스턴스 배열 생성
        // constructor
        Triangle(Point[] p) {
            this.p = p;
        }
        
        void draw() {
            System.out.printf("[p1=%s, p2=%s, p3=%s, color=%s]%n", p[0].getXY(), p[1].getXY(), p[2].getXY(), color);  // 인스턴스 메서드로 스트링타입을 대입 
        }
    }
    

     

'Java' 카테고리의 다른 글

제어자  (0) 2019.05.09
오버라이딩, Super, Super()  (0) 2019.05.08
메서드 호출  (0) 2019.05.07
참조형 매개변수, 참조형 반환  (0) 2019.05.07
변수의 종류(클래스변수, 인스턴스변수, 지역변수)  (0) 2019.05.07
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함