1. 클래스 간의 형변환
- 부모객체는 자식객체를 참조할수 있다.(업캐스팅) 하지만 자식객체에서 추가된 멤버는 접근할수없고, (오버라이딩된)메소드는 호출이 가능하다.
- 자식객체는 부모객체를 참조할수 있다. 단 이때는 자식타입으로 형변환 해야 한다.(다운캐스팅)
예)
int b=a; //가능
// 가능. 큰데이터형을 작은데이터형에 저장할때는 반드시 형변환해야 한다.
byte c=(byte)b;
MyShape sh = new MyShape();
MyRect mr = new MyRect();
MyTriangle mt = new MyTriangle();
//부모객체는 자식객체를 참조할수 있다.
MyShape mm = mr;
//자식객체는 부모객체를 참조할수 있다. 단 이때는 자식타입으로 형변환해야 한다.
MyRect mr1 = (MyRect)mm;
ex>
private String color;
public MyShape(String color)
{
this.color=color;
}
public String getColor()
{
return color;
}
public void draw(){}
}
class MyRect extends MyShape
{
public MyRect(String color){
super(color);
}
public void draw(){
System.out.println(getColor() + "색상의 사각형을 그려요!");
}
public void move(){
System.out.println("사각형을 이동하세요!");
}
}
class Test01_reference
{
public static void main(String[] args)
{
MyRect mr = new MyRect("Red");
MyShape ms = mr;
ms.draw();
ms.getColor();
MyShape ms1 = new MyRect("Red");
ms1.draw();
ms1.getColor();
ms1.move(); // 오류 발생함. 자식만 존재하고 부모는 없기때문에
MyRect mr1 = (MyRect)ms;
mr1.move();
}
}
2. 다형성(Polymorphism)
- 같은 종의 생물이지만 모습이나 고유한 특징이 다양한 성질을 갖는것
예:오버로딩,오버라이딩,..
ex>
//도형색상
private String color;
public MyShape(String color){
this.color=color;
}
public String getColor(){
return color;
}
//도형그리기기능
public void draw(){
}
}
class MyRect extends MyShape
{
public MyRect(String color){
super(color);
}
//오버라이딩
public void draw(){
System.out.println(getColor()+"색상의 사각형을 그려요!");
}
public void moveRect(){
System.out.println("사각형을 이동해요!");
}
}
class MyCircle extends MyShape
{
public MyCircle(String color){
super(color);
}
public void draw(){
System.out.println(getColor()+"색상으로 타원을 그려요!");
}
public void moveCircle(){
System.out.println("타원을 이동해요!");
}
}
class Test02_polymorphism
{
public static void main(String[] args)
{
MyRect mr=new MyRect("빨강");
MyCircle mc=new MyCircle("파랑");
//printer(mr);
//printer(mc);
printer1(mr);
printer1(mc);
}
public static void printer(MyShape ms)
{
System.out.println("프린터로 아래 도형을 출력해요!");
ms.draw();
}
public static void printer1(MyShape ms)
{
System.out.println("프린터로 아래 도형을 출력해요!");
ms.draw();
//ms가 MyRect타입의 객체냐?
if(ms instanceof MyRect)
{
MyRect mm=(MyRect)ms;
mm.moveRect();
}
//ms가 MyCircle타입의 객체냐?
if(ms instanceof MyCircle)
{
MyCircle mm=(MyCircle)ms;
mm.moveCircle();
}
}
// public static void printer(MyRect mr){
// System.out.println("프린터로 아래 도형을 출력해요!");
// mr.draw();
// }
// public static void printer(MyCircle mc){
// System.out.println("프린터로 아래 도형을 출력해요!");
// mc.draw();
// }
}
'JAVA' 카테고리의 다른 글
패키지 (0) | 2014.09.12 |
---|---|
추상 클래스 - 메소드 / 인터페이스 / Object (0) | 2014.09.12 |
오버라이딩 / final의 용도 (0) | 2014.09.12 |
상속 (0) | 2014.09.12 |
this (0) | 2014.09.12 |