[Java] 다형성

rara_kim·2022년 6월 12일
0

Java

목록 보기
9/39

다형성(Polymorphism)

다형성이란?

다형성(Polymorphism)이란 한 객체가 여러가지 타입을 가질 수 있는 것을 의미한다.
부모 클래스 타입의 참조변수로 자식 클래스 타입의 인스턴스를 참조할 수 있다.

다형성은 상속, 추상화와 더불어 객체 지향 프로그래밍을 구성하는 중요한 특징 중 하나이다.


instanceOf

자바에서는 instanceOf 연산자를 제공하여, 참조변수가 참조하고 있는 인스턴스의 실제 타입을 확인할 수 있다.

//부모 클래스
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");
    }
}


public class Main{
	pulic static void main(String[] args) {
        Person pe1 = new Person();
        Student st1 = new Student();
        Person pe2 = new Student();
        
        System.out.println(pe1 instanceof Person);    //true
        System.out.println(pe1 instanceof Student);   //false

        System.out.println(st1 instanceof Student);   //true
        System.out.println(st1 instanceof Person);    //true

        System.out.println(pe2 instanceof Person);    //true
        System.out.println(pe2 instanceof Student);   //true
	}
}
profile
느리더라도 꾸준하게

0개의 댓글