[상속-7] 오버라이딩-1 / 연습문제

seratpfk·2022년 8월 1일
0

JAVA

목록 보기
58/96

메소드 오버라이딩

  • 부모클래스에 taste가 있지만 맛이 다르기 때문에 메소드를 새로 다시 만들어야 함.

Coffee클래스(메인메소드 없음)

	public void taste() {
	}

Espresso클래스(메인메소드 없음)

public class Espresso extends Coffee {
	@Override
	public void taste() {
		System.out.println("쓰다");
	}
}

EspressoMain클래스(메인메소드 설정)

		Espresso espresso = new Espresso();
		espresso.taste();

출력:
쓰다

연습문제

  • 에스프레소에 extraWater를 추가하면 Americano
  • 에스프레소에 milk를 추가하면 CafeLatte
  • 각 taste() 작성

Americano클래스(메인메소드 없음)

public class Americano extends Espresso {
	private int extraWater;
	@Override
	public void taste() {
		System.out.println("덜 쓰다");
	}
}

CafeLatte클래스(메인메소드 없음)

public class CafeLatte extends Espresso {
	private int milk;
	@Override
	public void taste() {
		System.out.println("부드럽다");
	}
}

Main클래스(메인메소드 없음)

		Americano americano = new Americano();
		americano.taste();
	CafeLatte cafeLatte = new CafeLatte();
	cafeLatte.taste();

출력:
덜 쓰다
부드럽다


0개의 댓글