728x90
instanceof
객체가 어떤 클래스인지, 어떤 클래스를 상속 받았는지 객체의 타입을 확인할 때 사용한다.
boolean result = 객체 instanceof 타입;
boolean result = parent instanceof Child
좌항의 객체가 우항의 타입이면 true, 아니면 false를 산출한다.
강제 타입 변환하기 전 매개값이 맞는지 여부를 확인하기 위해 사용한다.
예제 코드
package ch07.sec09;
public class Person {
// 필드 선언
public String name;
// 생성자 선언
public Person(String name) {
this.name = name;
}
// 메소드 선언
public void walk() {
System.out.println("걷다");
}
}
package ch07.sec09;
public class Student extends Person {
public int studentNo;
public Student(String name, int studentNo) {
super(name);
this.studentNo = studentNo;
}
public void study() {
System.out.println("공부함");
}
}
package ch07.sec09;
public class InstanceOfExample {
public static void personInfo(Person person) {
// main() 메소드에서 바로 호출하기 위해 정적 메소드 선언
System.out.println("name : " + person.name);
person.walk();
// person이 참조하는 객체가 Student 타입일 경우
// student 변수에 대입(타입 변환 발생)
// Java 12부터 사용 가능
if (person instanceof Student student) {
System.out.println("student.studentNo = " + student.studentNo);
student.study();
}
}
public static void main(String[] args) {
Person p1 = new Person("이름");
personInfo(p1);
// name : 이름
// 걷다
System.out.println();
Person p2 = new Student("이름", 10);
personInfo(p2);
// name : 이름
// 걷다
// student.studentNo = 10
// 공부함
}
}
728x90
'IT > Java' 카테고리의 다른 글
[Java] Interface (0) | 2024.03.11 |
---|---|
[Java] abstract class & method (0) | 2024.03.08 |
[Java] 다형성(Polymorphism) (0) | 2024.03.08 |
[Java] 자동 타입 변환 & 강제 타입 변환 (0) | 2024.03.08 |
[Java] Method Overriding (0) | 2024.03.07 |