반응형

5.4> main() 함수를 다음과 같이 수행할 수 있도록 하기 위한 CPoint 클래스와 CColorPoint 클래스를 작성하고 전체 프로그램을 완성하라. CColorPoint 클래스의 어떤 메소드에서도 System.out.println()을 호출해서는 안 된다. CPoint 클래스는 생성자가 오직 하나뿐이다.


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
32
package HW1_JAVA;
class CPoint{ //class CPoint 선언
    int a; int b; String s;  //int형 변수 a,b 와 String s 선언
    protected CPoint(int a, int b){ //int a와 int b를 argument 로 갖는 생성자
        this.a=a; this.b=b; this.s=""//this.a에 a대입 this.b에 b 대입 s에 "" 대입(색깔들어갈자리)
    }
    void show(){
        System.out.println("("+a+","+b+")"+s); // a와 b와 s를 출력하는 메소드 show
    } //toString 메소드는 Object 클래스에 속한다. 
    public String toString(){ //메소드 오버라이딩 시 슈퍼 클래스 메소드의 접근지정자보다 접근 범위가 좁아질 수 없다.
        return "("+a+","+b+")"+" 입니다";
    } //toString : println의 인자로 객체의 레퍼런스 변수가 전달되면 해당 인스턴스의 toString 메소드가 호출되면서
    } // 리턴값으로 반환되는 문자열이 나온다.
class CColorPoint extends CPoint{ //CPoint를 상속하는 클래스 CColorPoint
        CColorPoint(int a, int b,String s)
        {
            super(a,b); //CColorPoint의 슈퍼클래스인 CPoint의 생성자 호출
            this.s=s; // this.s에 인자 s 대입
        }
    }
public class PointCl {
    public static void main(String[] args) {
        CPoint a,b; //CPoint 형 클래스를 가리키는 레퍼런스 변수 a,b
        a=new CPoint(2,3); // CPoint 클래스의 객체 생성(인자는 2,3) 레퍼런스 변수는 a
        b=new CColorPoint(3,4,"red"); //업캐스팅된 CColorPoint 클래스의 객체를 가리키는 레퍼런스변수 b
        a.show(); //a.show 메소드 호출
        b.show(); //b.show 메소드 호출
        System.out.println(a); //a 출력인데 a.toString의 리턴값이 출력됨
        System.out.println(b); //b 출력인데 b.toString의 리턴값이 출력됨
    }
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > JAVA' 카테고리의 다른 글

메소드 오버라이딩  (0) 2017.06.18
추상 클래스  (0) 2017.06.18
ArrayUtility class  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18
돈 단위 나누기  (0) 2017.06.18

+ Recent posts