
한 타입의 참조변수를 통해 여러 타입의 객체를 참조할 수 있도록 만든 것이다.
public class InstanceOfExam {
public static void main(String[] args) {
Transport transport = new Transport();
System.out.println(transport instanceof Object); // true
System.out.println(transport instanceof Transport); // true
System.out.println(transport instanceof Bus); // false
Transport taxi = new Taxi();
System.out.println(taxi instanceof Object); // true
System.out.println(taxi instanceof Transport); // true
System.out.println(taxi instanceof Bus); // false
System.out.println(taxi instanceof Taxi); // true
}
}
class Transport {};
class Bus extends Transport {};
class Taxi extends Transport {};
public class PolymorphismExam {
public static void main(String[] args) {
Customoer customoer = new Customoer();
customoer.buySnack(new Icecream());
customoer.buySnack(new Candy());
System.out.println("현재 잔액은 " + customoer.money + "원 입니다.");
}
}
class Snack {
int price;
public Snack(int price){
this.price = price;
}
}
class Icecream extends Snack {
public Icecream(){
super(4000); // 상위 클래스인 Snack의 생성자를 호출
}
public String toString(){
return "아이스크림";
}
};
class Candy extends Snack {
public Candy(){
super(5000);
}
public String toString(){ // Object클래스의 toString()메서드 오버라이딩
return "사탕";
}
};
class Customoer {
int money = 50000;
void buySnack(Snack snack){
if(money < snack.price){
System.out.println("잔액이 부족합니다.");
return;
}
money = money - snack.price;
System.out.println(snack + "을 구매했습니다.");
}
}
// 출력 결과
// 아이스크림을 구매했습니다.
// 사탕을 구매했습니다.
// 현재 잔액은 41000원 입니다.
객체의 공통적인 속성과 기능을 추출하의 정의하는 것이다.
기존 클래스들의 공통적인 요소를 추려서 상위 클래스를 만들어내는 것이다.
메서드 시그니처만 존재하고 바디가 선언되지 않은 추상 메서드를 포함하는 클래스
abstract class Transportation {
public String name;
public abstract void horn();
}
class Car extends Transportation { // Transportation 클래스로부터 상속
public Car(){
this.name = "자동차";
}
public void horn(){ // 메서드 오버라이딩을 통한 구현부 완성
System.out.println("빵빵");
}
}
class Bicycle extends Transprotation { // Transportation 클래스로부터 상속
public Bicycle(){
this.name = "자전거";
}
public void horn(){
System.out.println("따르릉"); // 메서드 오버라이딩을 통한 구현부 완성
}
}
class CarExam {
public static void main(String[] args){
Transportation car = new Car();
car.horn();
Bicycle bicycle = new Bicycle();
bicycle.horn();
}
}
// 출력 결과
// 빵빵
// 따르릉
final class FinalExam { // 확장 및 상속 불가능한 클래스
final int a = 10; // 변경 불가능한 상수
final int sum(){ // 오버라이딩 불가능한 메서드
final int lv = a; // 상수
return a;
}
}
| 위치 | 의미 |
|---|---|
| 클래스 | 변경 또는 확장 불가능한 클래스, 상속 불가능 |
| 메서드 | 오버라이딩 불가능 |
| 변수 | 값 변경이 불가능한 상수 |
추상 클래스처럼 완성되지 않은 불완전한 것으로 다른 클래스를 작성하는데 도움을 줄 목적으로 작성하는 것이다.
public interface InterfaceName {
public static final int first = 5; // 인터페이스 인스턴스 변수 정의
final int second = 10; // public static 생략
static int third = 15; // public, final 생략
public abstract String getNumber();
void call(); // public abstract 생략
}
class 클래스명 implements 인터페이스명 {
// 인터페이스에 정의된 추상메서드를 구현
}