Java

[Java] 다형성

블로그 주인장 2023. 8. 8.

 

목차


    📢 다형성

    • 한 객체가 여러 가지 타입을 가질 수 있는 것이다.
    • 부모 클래스 타입의 참조 변수로 자식 클래스 인스턴스를 참조하는 것이다.
    class Person {
        public void print() {
            System.out.println("Person.print");
        }
    }
    class CollegeStudent extends Person {
        public void print() {
            System.out.println("CollegeStudent.print");
        }
    }
    public class Main {
    
        public static void main(String[] args) {
        
            Person p1 = new Person();
            Student s1 = new Student();
    
            //부모클래스 = 자식클래스(true)
            Person p2 = new Student();
            //자식클래스 = 부모클래스(false)
    //      Student s2 = new Person();
    
        }
    }

    📢 업캐스팅과 다운캐스팅

    • 업캐스팅 : 자식 클래스를  부모 클래스에 타입으로 형변환시켜준다.
    • 다운캐스팅 : 부모클래스를 자식클래스 타입으로 형변환시켜준다.
    class Person {
        public void print() {
            System.out.println("Person.print");
        }
    }
    class CollegeStudent extends Person {
        public void print() {
            System.out.println("CollegeStudent.print");
        }
    }
    public class Main {
    
        public static void main(String[] args) {
        
           Person pp1 = null;
           Student ss1 = null;
           Person pp3 = new Student(); //업캐스팅
           ss1 = (Student)pp3;         //다운캐스팅
        }
    }

    📢 instanceof

    • 실제 참조하고 있는 인스턴스 타입을 확인
    class Person {
        public void print() {
            System.out.println("Person.print");
        }
    }
    class CollegeStudent extends Person {
        public void print() {
            System.out.println("CollegeStudent.print");
        }
    }
    public class Main {
    
        public static void main(String[] args) {
        
            System.out.println("== instanceof ==");
            Person pe1 = new Person();
            Student st1 = new Student();
    
            // Person이라는 클래스 안에 pe1이 속해있는지 확인(true)
            System.out.println(pe1 instanceof Person);
    
            // Student이라는 클래스 안에 pe1이 속해있는지 확인(false)
            System.out.println(pe1 instanceof Student);
    
            // Person이라는 클래스 안에 st1이 속해있는지 확인(true)
            // Student가 Person의 자식클래스 이기 때문에 true이다.
            System.out.println(st1 instanceof Person);
    
            // Student이라는 클래스 안에 st1이 속해있는지 확인(true)
            System.out.println(st1 instanceof Student);
        }
    }

     

    반응형

    'Java' 카테고리의 다른 글

    [Java] 추상클래스  (0) 2023.08.09
    [Java] 상속과 오버라이딩  (0) 2023.08.08
    [Java] 클래스와 객체(2)  (0) 2023.08.08

    댓글