티스토리 뷰

Java

instanceof

techbard 2016.07.13 19:02



# Animal.java


public class Animal {


    private String name;


    public Animal(String name) {

this.name = name;

    }


    public String getName() {

return name;

    }


    public String say() {

return "unknown";

    }

}



# Dog.java


public class Dog extends Animal {


    public Dog(String name) {

super(name);

    }


    @Override

    public String say() {

return "waf! waf!";

    }

}



# Main.java


public class Main {


    public static void main(String[] args) {

Animal dog = new Dog("fido");

showAnimalType(dog);

    }

    

    private static void showAnimalType(Animal a) {

Class theClass = a.getClass();

String className = theClass.getSimpleName();

Class parentClass = theClass.getSuperclass();

String parentClassName = parentClass.getSimpleName();

System.out.println("Class name is " + className);

System.out.println("Parent class name is " + parentClassName);

if (a instanceof Animal) {

   System.out.println("It's an Animal");

}

if (a instanceof Dog) {

   System.out.println("It's a Dog");

}

System.out.println("This animal says: " + a.say());

    }

}



# 결과


Class name is Dog

Parent class name is Animal

It's an Animal

It's a Dog

This animal says: waf! waf!


댓글
댓글쓰기 폼
공지사항
Total
394,932
Today
3
Yesterday
28
«   2018/11   »
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
글 보관함