Person person = new Person();
// 부모 타입으로 자식 클래스 객체 생성
// 배열로 관리하며 중복 메소드 호출하는 등의 방법을 사용할 수 있음
Person student = new Student();
Person teacher = new Teacher();
런타임에 참조 데이터 타입이 아닌 실제 객체 타입의 메소드를 실행
int, double , ...)이 아닌 참조 데이터 타입은 객체가 저장된 메모리의 주소 값을 담게 됨Person student = new Student();
((Student) student).study();instanceof 연산을 통한 객체 판별A instanceof B의 의미truefalsefalseinstanceof하면 컴파일 에러true는 검사한 타입으로 형변환을 해도 아무 문제가 없다는 뜻이고 false는 형변환이 불가능하거나 문제가 생긴다는 것을 뜻함false인터페이스는 구현되지 않은 메소드로 구성되어 있다.
public interface INTERFACE_NAME { // 인터페이스 선언
public final static Data_Type CONST_NAME = CONST_VALUE; // 상수 선언
public Return_Type METHOD_NAME (PARAM_1, PARAM_2); //메소드 선언
}
public final static이다.final static 키워드가 붙는 변수는 상수이다.인터페이스를 구현하는 클래스에서 implements 이용하여 구현
인터페이스에 선언된 모든 추상 메소드를 override하여 구현해야 함.
// 문법
public class 클래스명 implements 인터페이스명 {
// 인터페이스에 선언된 메소드 구현
}
// 예제
public interface Flyable {
public void fly();
}
public class Bird implements Flyable {
public void fly() {
// fly() 메소드 구현
}
}
public class BirdTest {
Flyable fly = new Bird(); // Case 1: 클래스의 필드로 선언
BirdTest(Flyable fly) { // Case 2: 생성자 또는 메소드의 매개 변수로 선언
this.fly = fly;
}
public void methodA(Flyable fly) {
// ...implementation
}
public void methodB() { // Case 3: 생성자 또는 메소드의 로컬 변수로 선언
Flyable fly = new Bird();
}
}
extends 키워드 뒤에 올 수 있는 부모 클래스는 단 하나public class ChildClass extends ParentClass implements InterfaceOne, Interfacetwo {
// ...implementation
// 인터페이스의 추상 메소드 전부 구현하기
}
프로그램을 개발할 때 인터페이스를 사용해서 메소드를 호출하도록 했다면 구현 객체를 교체하기 용이해진다.
메소드 호출부는 수정할 필요 없이 구현 객체를 교체하는 것만으로 실행 결과를 다르게 할 수 있다는 점. 이것이 인터페이스의 다형성이다.
public interface Vehicle {
pubilc void drive();
}
public class Motorcycle implements Vehicle {
@Override
public void drive() {
System.out.println("부릉");
}
}
public class Bicycle implements Vehicle {
@Override
public void drive() {
System.out.println("영차영차");
}
}
public class Driver {
public void drive(Vehicle vehicle) { // 매개변수 다형성
vehicle.drive();
}
}
public class DriverTest {
public static void main(String[] args) {
Driver driver = new Driver();
Motorcycle mc = new Motorcycle();
Bicycle bc = new Bicycle();
driver.drive(mc); // 다형성
driver.drive(bc); // 다형성
}
}
double data = 5.2;
String dataToString = Double.toString(data);
abstract 키워드에 대해
추상 클래스에서 추상 메소드에는 abstract 키워드를 붙여줘야 한다 (컴파일 에러)
public abstract class AbstractClass {
public void methodA(); // Missing method body, or declare abstract
public abstract void methodB();
}
인터페이스에선 abstract 키워드를 붙이지 않아도 된다
public interface _Interface {
public abstract void methodA(); // Modifier 'abstract' is redundant for interface methods
public void methodB();
}