반응형
다형성
- OOP언어의 3번째 특징.
- 이론적으로 다양한 형태를 가질수 있는 성질
- 하나의 객체가 여러가지 유형으로 사용되는 것 (class 형변환을 의미한다)
- ⭐다형성은 상속을 전제조건으로 한다.
- 자식class가 부모class에 대입될 수 있다.
<변수를 예로 들면>
int num = 1;
double d = num;
-> int가 크기가 더 작기 때문에 double형으로 그냥 사용가능.
double d=3.14;
int num = (int)d;
-> d를 int형으로 형변환 해주는것은 double형이 더 크기 때문에.
💡 객체도 마찬가지다. 부모가 더 큰 class기 때문에 자식을 넣어서 사용가능하다
<다형성 사용 예시>
Student s = new Student();
Person p = s;
한줄로 사용하기 => Person p = new Student();
💡 부모클래스에 있는 기능만 사용가능
💡 오버라이딩 된 method가 있다면 먼저 실행된다. (우선적으로 적용되는 법칙)
❗ 다형성은 "클래스 형변환"이다.
➰ 다형성 알아보기
🔆main 클래스
package day15.poly.basic;
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.method01();//child에 없기때문에 부모의 method01
c.method02();//child에 있는 method02 ( 오버라이드 되었있음 )
c.method03();//child에 있는 method03
System.out.println("-----다형성-----");
/*
* 자식이 부모에 저장되는데, 부모님처럼 사용되지만
* 단, 자식의 오버라이딩된 메서드가 실행된다.
*/
Parent p = c;
p.method01(); //Perent class에 있는 method밖에 사용할 수 없다
p.method02(); //but, 오버라이드된 것은 우선적으로 사용하게 된다.(자식의 method02번 사용)
System.out.println(p == c); // 동일한 주소값을 나타냄.
System.out.println("------클래스 캐스팅------");
/*
* 다형성이 적용되면, 자식이 가지고 있던 본래의 기능을 사용할 수 없기 때문에.
* 클래스 캐스팅을 사용합니다.
*/
Child cc = (Child)p;
cc.method01();
cc.method02();
cc.method03();
System.out.println("-----주의 할 점-----");
/* 다형성이 적용된 객체만 캐스팅이 가능합니다 */
Parent pp = new Parent();
Child ccc = (Child)pp; //error;
}
}
🔆 부모클래스
package day15.poly.basic;
public class Parent {
public void method01() {
System.out.println("부모의 1번 메서드");
}
public void method02() {
System.out.println("부모의 2번 메서드");
}
}
🔆자식 클래스
package day15.poly.basic;
public class Child extends Parent{
//alt+shift+s Override Implement method
@Override
public void method02() {
System.out.println("오버라이드 된 2번 method");
}
public void method03() {
System.out.println("자식의 3번 method");
}
}
❗ 주의 할 점.
Parent p = new Child();
위와 같이 다형성을 사용한 p는 아래처럼 캐스팅을 사용하여 다시 자식으로 선언가능하지만,
Child c = (Child)p;
다형성을 사용하지 않은 아래와 같은 p는 다운 캐스팅 될 수없다. 에러..!
Parent p = new Parent();
Child c = (Child)p; //error
💡 method의 parameter값에도 부모class로 parameter값을 받도록 되어있다면 자식class의 값을 전달해 주어도 동작한다.
➰ Quiz - 다형성을 이용하여 cart에 물건담기(computer/radio/tv)
🔆main 클래스
package day15.quiz;
public class Main {
public static void main(String[] args) {
Computer com = new Computer();
Radio radio = new Radio();
Tv tv = new Tv();
MyCart cart = new MyCart(5000);
//cart.buy(com);
//cart.info();
cart.buy(com);
cart.buy(com);
cart.buy(tv);
cart.buy(com);
cart.buy(radio);
cart.buy(radio);
cart.buy(radio);
cart.buy(tv);
cart.buy(tv);
cart.buy(tv);
cart.buy(tv);
//cart.info();
}
}
🔆MyCart 클래스
package day15.quiz;
import java.util.Arrays;
public class MyCart {
/*
철수는 TV객체, Radio객체, Computer객체를 전달받아서 계산하는 Cart클래스를 만드려고한다.
Product클래스는 부모클래스 이다.
Tv, Radio, Computer는 자식클래스 이다.
Product클래스에는 필요한 변수가 선언되어 있고 getter, setter가 생성되어 있다.
*/
private int money;
private Product[] cart = new Product[1]; //상품을 저장할 배열
private int i = 0;
//2. MyCart의 생성자는 money만 받아서 초기화
public MyCart(int money) {
this.money = money;
}
/*
* 3. buy(모든 상품을 받도록 선언)
* ************객체의 getter메서드의 활용*************
* 가진돈과 전달된 물건객체의 가격을 비교해서 돈이 적으면 "금액부족" 출력후에 종료하세요.
* 가진돈이 충분하면 물건의 가격을 money에서 차감하고 add(상품) 메서드를 호출합니다.
*/
public void buy(Product p) {
if(this.money < p.getPrice()) {
System.out.println("금액부족");
}else {
//System.out.println(p.getName() + " 구매 되었습니다.");
money -= p.getPrice();
add(p);
}
}
/*
* 4. add(모든 상품을 받도록 선언)
* *************배열의 복사**************
* 만약 i의 값이 장바구니의 크기보다 같거나 크다면
* 기존의 장바구니보다 크기가 * 2큰 배열을 생성.
* 기존의 장바구니 값을 새로운 배열에 복사.
* 새로운 장바구니를 기존의 장바구니와 바꾼다.
*
* 상품(매개변수)을 장바구니(배열)에 담는다.
*
* info()메서드 호출
*/
private void add(Product p) {
/* 뉴카트 생성해서 배열크기 2배 더 크게 만들고, 기존 장바구니에 들어있는 값 복사 */
Product[] new_cart;
if(cart.length <= i) {
new_cart = new Product[cart.length*2];
new_cart = Arrays.copyOf(cart, new_cart.length);
/* 기존 장바구니에 크기를 조절하고 new_cart에 있는 것을 바꾸기.*/
cart = new Product[new_cart.length];
cart = Arrays.copyOf(new_cart, cart.length);
}
/* 장바구니에 물건담기 */
cart[i] = p;
i++;
System.out.println("----- 장바구니 목록 -----");
this.info();
System.out.println("----------------------");
}
/*
* 5.info()
* - 장바구니 안에 담긴 물건의 목록(name)을 출력한다.
* - 남은금액 출력
* 출력예시: TV TV Computer Radio ......
* 남은금액: 500
* 메인에서 buy메서드 실행
*
*/
public void info() {
for(Product p : cart) {
if(p == null) break;
System.out.print(p.getName() + " ");
}
System.out.println();
System.out.println("남은 금액:" + this.money);
}
}
🔆 product 클래스 (부모클래스)
package day15.quiz;
public class Product {
//상품의 부모클래스 - 수정x
private int price;
private String name;
public Product(int price, String name) {
this.price = price;
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
🔆computer(자식클래스1)
package day15.quiz;
public class Computer extends Product {
//가격 600원 이름은 com
//get, set메서드는 자동으로 상속됩니다
public Computer() {
super(600, "com");
}
}
🔆Radio(자식클래스1)
package day15.quiz;
public class Radio extends Product {
//Radio의 생성자는 기본생성자로 만들고, super를 통해서 가격 500원, 이름은 radio로 저장
//get, set메서드는 자동으로 상속됩니다
public Radio() {
super(500, "radio");
}
}
🔆Tv(자식클래스1)
package day15.quiz;
public class Tv extends Product {
//가격 400원 이름은 tv
//get, set메서드는 자동으로 상속됩니다
public Tv() {
super(400, "tv");
}
}
🔆 결과값(길어서 일부만 첨부해놓았다, 이런식으로 출력)
----- 장바구니 목록 -----
com com tv com radio radio radio
남은 금액:1300
----------------------
----- 장바구니 목록 -----
com com tv com radio radio radio tv
남은 금액:900
----------------------
----- 장바구니 목록 -----
com com tv com radio radio radio tv tv
남은 금액:500
----------------------
----- 장바구니 목록 -----
com com tv com radio radio radio tv tv tv
남은 금액:100
----------------------
금액부족반응형
'국비지원 > JAVA' 카테고리의 다른 글
| [JAVA] 16-2. singleton Design Pattern & final Keyword & 상수(constant) & abstract (0) | 2022.10.13 |
|---|---|
| [JAVA] 16-1. 정적제한자 static (0) | 2022.10.13 |
| [JAVA] 14-2. 접근제어자 & 객체와 배열 (0) | 2022.10.11 |
| [JAVA] 14-1. super keyword (0) | 2022.10.11 |
| [JAVA] 13-3. this keyword (0) | 2022.10.07 |