다형성 관련 내용
2020.04.22. 과제 - 객체지향[OOP] 프로그래밍 특징 / 5대 원칙
객체지향 프로그래밍의 특징 1. 캡슐화( Encapsulation ) 1) '은닉화'라고도 하며 데이터(속성)와 데이터를 처리하는 함수를 하나로 묶은 것을 의미한다. 2) 외부에서 잘못된 접근을 할 경우 객체의 데�
srk911028.tistory.com
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//다형성 : 다양한 형태의 성질을 갖는다.
//부모 클래스의 참조 변수로 하위 클래스의 객체를 참조할 수 있다
//->부모 클래스 인스턴스의 자식 클래스의 인스턴스를 넣을 수 있다.
//컨트롤 + 시프트 + o(영어) 하면 필요한 라이브러리 자동 임포트
Scanner sc = new Scanner(System.in);
System.out.print("바나나: 1, 복숭아: 2 ");
int input = sc.nextInt();
Fruit fruit=null;
if(input==1)
{
fruit = new Banana();
}
else
{
fruit = new Peach();
}
fruit.Show();
//fruit 인스턴스가 peach의 인스턴스인가?
if(fruit instanceof Peach)
{
System.out.println("어피치 좋아");
}
}
}
public class Fruit {
String name;
int price;
int fresh;
public void Show()
{
System.out.println("이름: "+this.name);
System.out.println("가격: "+this.price);
System.out.println("신선도: "+this.fresh);
}
}
public class Peach extends Fruit{
public Peach() {
price = 1500;
name ="복숭아";
fresh =75;
}
}
public class Banana extends Fruit{
public Banana() {
price = 1000;
name ="바나나";
fresh = 50;
}
}


'JAVA > STUDY' 카테고리의 다른 글
9. 인터페이스 (0) | 2020.09.11 |
---|---|
8. 추상 / Final (0) | 2020.09.10 |
7. 클래스 / 상속 (0) | 2020.09.10 |
6. 반복문과 재귀함수 (팩토리얼, 피보나치) (0) | 2020.09.09 |
5. 입력 / 파일 입력 (0) | 2020.09.09 |