다형성
- 한 객체가 여러 가지 타입을 가질 수 있는 것
- 부모클래스 타입의 참조 변수로 자식클래스 인스턴스 참조
class Person {}
class Student extends Person {} // 자식 클래스
Person p1 = new Student(); // 자식 클래스에 객체를 만들어 할당
// Student s1 = new Person(); - 불가능.
instanceof
class Person {}
class Student extends Person {}
Person p1 = new Student();
// Student s1 = new Person();
System.out.println(p1 instanceof Person);
// 출력으로 써주면, p1이 Person의 객체인지 아닌지 확인 가능
class Person {
public void print() {
System.out.println("Person.print");
}
}
class Student extends Person {
public void print() {
System.out.println("Student.print");
}
public void print2() {
System.out.println("Student.print2");
}
}
class CollegeStudent extends Person {
public void print() {
System.out.println("CollegeStudent.print");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("== 다형성 ==");
Person p1 = new Person();
Student s1 = new Student();
Person p2 = new Student();
p1.print();
s1.print();
s1.print2();
p2.print();
Person p3 = new CollegeStudent();
p3.print();
System.out.println("== 타입 변환 ==");
Person pp1 = null;
Student ss1 = null;
Person pp2 = new Person();
Student ss2 = new Student();
Person pp3 = new Student();
pp1 = pp2;
pp1 = ss2;
ss1 = ss2;
ss1 = (Student)pp3;
System.out.println("== instanceof ==");
Person pe1 = new Person();
Student st1 = new Student();
Person pe2 = new Student();
Person pe3 = new CollegeStudent();
System.out.println(pe1 instanceof Person);
System.out.println(pe1 instanceof Student);
System.out.println(st1 instanceof Student);
System.out.println(st1 instanceof Person);
System.out.println(pe2 instanceof Person);
System.out.println(pe2 instanceof Student);
System.out.println(pe3 instanceof Person);
System.out.println(pe3 instanceof CollegeStudent);
if (pe1 instanceof Student) {
Student stu1 = (Student) pe1;
}
if (st1 instanceof Person) {
Person per1 = (Person) st1;
}
}
}
class Car {
Car(){}
public void horn() {
System.out.println("빵빵!");
}
}
class FireTruck extends Car {
public void horn() {
System.out.println("위이잉!");
}
}
class Ambulance extends Car {
public void horn() {
System.out.println("삐뽀삐뽀!");
}
}
public class Practice {
public static void main(String[] args) {
Car car = new Car();
Car car2 = new FireTruck();
Car car3 = new Ambulance();
car.horn();
car2.horn();
car3.horn();
}
}