[Java]다형성

이다혜·2023년 10월 23일
0

Java

목록 보기
4/23
post-thumbnail

📌 다형성이란?

  • 하나의 객체가 여러 가지 타입을 가질 수 있는 것을 의미

  • 부모 클래스 타입의 참조 변수로 자식 클래스 타입의 인스턴스를 참조할 수 있습니다.

예제

class Parent {...}
class Child extends Parent{...}

Parent p1 = new Child(); // 허용
Child c1 = new Parent(); // 오류

📌 부모클래스 타입에서 자식 클래스 타입으로의 타입 변환

(변환할타입의클래스이름) 변환할참조변수

예제

class Parent { ... }
class Child extends Parent { ... }

Parent p1 = new Child(); //생략 가능
Child c1 = (Child)(new Parent()); //생략 불가능

📌 instanceOf로 확인

참조변수 instanceof 클래스이름

예제

Parent p = new Child();
System.out.println(p instanceof Object); // true
System.out.println(p instanceof Parent); // true
System.out.println(p instanceof Child);  // true

0개의 댓글