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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
public class Ex {
public static void main(String[] args) {
// 인스턴스 생성후 메서드 ㅗ출
Circle c = new Circle();
Rectangle r = new Ractangle();
Triangle t = new Triangle();
c.draw();
r.draw();
t.draw();
// 업캐스팅
Shape s = new Circle();
s.draw();
Shape s = new Ractangle();
s.draw();
Shape s = new Triangle();
s.draw();
//polymorphismDraw()메서드를 이용해 각도형의 메서드 호출
polymorphismDraw(c);
polymorphismDraw(r);
polymorphismDraw(r);
//배열을 사용하여 업캐스팅을 활용하는 방법
// 세개의 인스턴의를 하나의 Shape 타입 배열에 저장
Shape[] sArr = {c,r,t};
for(int i = 0; i<sArr.length ; i++) {
sArr[i].draw();
}
// 향상된 for문
for(shape s1 : sArr) {
s1.draw();
}
}
// 각 인스턴스 내의 draw() 메서드를 호출하는 메서드 정의
// 상속관계를 일때 Shape 타입 변수 하나만으로 draw() 메서드 호출가능
public static void polymorphismDraw(Shape s) {
s.draw();
}
}
class Shape {
public void draw(){
System.out.println("도형 그리기");
}
}
class Circle{
@Override //annotaion
public void draw() {
System.out.println("원 그리기");
}
}
class Rectangle{
System.out.println("사각형 그리기");
}
class Triangle{
System.out.println("삼각형 그리기");
}
|
cs |
'Language > Java' 카테고리의 다른 글
추상메서드(abstract method) (0) | 2020.06.11 |
---|---|
instanceof 연산자 (0) | 2020.06.09 |
레퍼런스(참조형) 형변환 (0) | 2020.06.05 |
생성자 super() (0) | 2020.06.05 |
레퍼런스 super (0) | 2020.06.05 |