개발공부

다형성

pumaclass 2024. 7. 28. 16:04

다형성이란 조상타입 참조변수로 자손타입의 객체를 다루는것

 

 

Tv라는 부모 객체를 만들고 SmartTv라는 자식 객체를 만들어

부모의 변수를 자식 객체가 다룰수있다.

 

위 예시로 예를 들자면 인스턴스 생성때 Tv t = new SmartTv()로 생성이 가능하다.

하지만 SmartTv st = new Tv()로는 생성이 불가능하다.

 

예시의 부모는 5개의 필드를 갖고있고 자식은 2개의 필드를 갖고있다.

 

자식 클래스가 extends 함수를 통해 부모객체를 불러오면

총 7개를 필드를 갖게된다.

 

위 예시를 인스턴스화 하게되면

Tv t = new SmartTv() 로 인스턴스화 하여 사용해도 된다.

이것이 다형성이다.

 

예제

class Person{
	void print(){
    System.out.println("Person클래스의 print 메소드");
    }
  }
  
class Student expends Person{
	@Override
    public void print(){
    System.out.println("Student클래스의 print 메소드");
    }
}

public class Test{
	public static void main(string[] args){
    	Person p1 = new Person(); //부모의 인스턴스화
        Student st1 = new Student(); //자식의 인스턴스화
        Person p2 = new Student(); // 부모객체로 자식 객체 선언 가능(반대로는 불가)
        
        p1.print();
        st1.print();
        p2.print();
        
    }
}

 

Instanceof 연산자

1. 다형성으로 변수가 실제 어떤 인스턴스를 참조하고 있는지 확인할때 사용.

2. 참조변수 Instanceof 클래스 이름으로 사용.

    인스턴스가 요청한 클래스를 사용중이면 true로 출력됨

class Person{
	void print(){
    System.out.println("Person클래스의 print 메소드");
    }
  }
  
class Student expends Person{
	@Override
    public void print(){
    System.out.println("Student클래스의 print 메소드");
    }
}

public class Test{
	public static void main(string[] args){
    	Person p1 = new Person(); //부모의 인스턴스화
        Student st1 = new Student(); //자식의 인스턴스화
        Person p2 = new Student(); // 부모객체로 자식 객체 선언 가능(반대로는 불가)
        
        System.out.println("p1");
		System.out.println(p1 instanceof Object);
        System.out.println(p1 instanceof Person);
        System.out.println(p1 instanceof Student);
        
        System.out.println("p2");
		System.out.println(p2 instanceof Object);
        System.out.println(p2 instanceof Person);
        System.out.println(p2 instanceof Student);       
    }
}

 

출력결과는 아래와 같이 출력된다.

p1

true

true

false

p2

true

true

true

 

'개발공부' 카테고리의 다른 글

for문을 이용한 구구단 만들기  (0) 2024.08.01
for문에 대해  (0) 2024.07.31
필수 수강 목록  (0) 2024.07.27
정말 쉽다 너 switch  (0) 2024.07.25
나를 괴롭히는 for문  (1) 2024.07.24