반응형
package dayday13;
/*
* instanceof 연산자
* -> 객체명 instanceof 클래스명
* -> 해당 객체가 해당 클래스인지 boolean으로 판단
*
*/
class Person{
String name;
int age;
void sayHello(Person p){
System.out.println("좋은아침입니다");
}
}
class Student extends Person{
//같은학생끼리는 안녕, 교수님을 만나면 안녕하세요.
@Override
void sayHello(Person p) {
// TODO Auto-generated method stub
if(p instanceof Student){
System.out.println(p.name + " 안녕~ 굿모닝");
}else if(p instanceof Professor){
System.out.println(p.name + "교수님 안녕하세요");
}
}
}
class Professor extends Person{
}
public class test01 {
public static void main(String[] args) {
Student st1 = new Student();
st1.name ="피카츄";
st1.age = 10;
Student st2 = new Student();
st2.name ="푸린";
st2.age = 20;
Professor pro = new Professor();
pro.name ="고길동";
pro.age = 30;
st1.sayHello(st2);
st1.sayHello(pro);
}
}
반응형
'IT > Programming' 카테고리의 다른 글
[JAVA] polymorphism(다형성), up&down casting 사용 예제 (0) | 2023.04.21 |
---|---|
[JAVA] Abstract class를 사용한 미니게임[탱크vs스나이퍼] 예제 (0) | 2023.04.20 |
[JAVA] java.lang package class 사용 예제 (0) | 2023.04.20 |
[JAVA] Wrapper class 사용 예제 (0) | 2023.04.20 |
[JAVA] String class 사용 예제 (0) | 2023.04.20 |