반응형

5.5>추상 클래스의 서브 클래스 만들기에 필요한 추상 메소드 오버라이딩과 super()의 사용에 관한 문제이다. 다음과 같은 MyPoint 추상 클래스가 있다.




MyPoint를 상속받는 MyColorPoint 클래스를 작성하라. MyColorPoint의 생성자는 MyColorPoint(int x, int y, String color)로 하라. 그리고 다음과 같은 main() 메소드를 삽입하여 실행되도록 하라.





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
33
34
35
36
37
38
39
40
package HW1_JAVA;
abstract class MyPoint{ // 추상 클래스 MyPoint
    int x; int y;  //int형 변수 x,y 선언
    public MyPoint(int x,int y){  //생성자 MyPoint int형 변수인 인자 x,y
        this.x=x; this.y=y; //객체의 x에 인자 x 대입, 객체의 y에 인자 y 대입
    }
    protected abstract void move(int x,int y); //추상 메소드 move,int형 인자 x,y
    protected abstract void reverse(); //추상 메소드 reverse
    protected void show(){ // 객체의 x와 y를 출력하는 메소드 show
        System.out.println(x+","+y);
    }
}
class MyColorPoint extends MyPoint{  //MyPoint를 상속하는 MyColorPoint 클래스
    String s; //스트링형 오브젝트 s
    public MyColorPoint(int x, int y, String Color){ //생성자 인자는 int형 x,y와 string Color
        super(x,y); //슈퍼클래스의 생성자 호출
        this.s=Color; //String 레퍼런스 변수 Color가 가리키는 문자열을 this.s가 가리키게함
    }
    protected void move(int x,int y){ //상속받은 추상 메소드 오버라이딩
        this.x=x; this.y=y; //객체의 x에 인자 x 대입, 객체의 y에 인자 y 대입
    }
    protected void reverse(){ //상속받은 추상 메소드 오버라이딩
        int temp; // int형 변수 temp, 빈 물컵 역할
        temp=this.x;  //x와 y를 스왑하는 과정
        this.x=this.y;
        this.y=temp;
    }
    protected void show(){ //슈퍼클래스의 메소드 show 오버라이딩
        System.out.println(x+","+y+","+s);  //x와 y와 s를 출력하는 메소드 show
    }
}
public class Abstract {
    public static void main(String[] args) {//MyPoint형 객체를 가리키는 레퍼런스 변수 p
        MyPoint p=new MyColorPoint(2,3,"blue"); //MyColorPoint클래스의 객체 생성, 업캐스팅
        p.move(34); // 동적 바인딩에 의해 MyColorPoint에서 오버라이딩한 메소드move가 호출됨
        p.reverse(); //동적 바인딩에 의해 MyColorPoint에서 오버라이딩한 메소드reverse가 호출됨
        p.show(); //동적 바인딩에 의해 MyColorPoint에서 오버라이딩한 메소드 show가 호출됨
    }
}
 
cs


반응형

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

대문자 개수 세기  (0) 2017.06.19
메소드 오버라이딩  (0) 2017.06.18
상속 클래스  (0) 2017.06.18
ArrayUtility class  (0) 2017.06.18
직사각형 클래스  (0) 2017.06.18

+ Recent posts