donaricano-btn

 Instanceof

- instanceof operator is used to test whether the object is an instance of the specified type

- It is also known as type comparison operator

It returns either true or false


1. Example

1
2
3
4
5
6
public class Test{
    public static void main(String[]args){
        Test a = new Test();
        System.out.println(a instanceof Test);
    }
}

- true

2. instanceof in java with a variable that have null value

1
2
3
4
5
6
public class Test{
    public static void main(String[]args){
        Test a = null;
        System.out.println(a instanceof Test);
    }
}
 

- false

3. Downcasting with java instanceof operator

1) Downcasting

When subclass type refers to the object of Parent class, it is known as downcasting

1
Dog d = new AnImal(); //Compilation error
 

1
Dog d = (Dog) new Animal() // ClassCastException
 

2) Possibility of downcasting with instanceof

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package statics;
 
class Animal{
     
}
 
class Dog extends Animal{
     
    static void method(Animal a){
        if(a instanceof Dog){
            Dog d = (Dog)a;//down
        }
    }
     
}
 
public class Test{
    public static void main(String[]args){
        Animal a = new Dog();
        Dog.method(a);
    }
}
 

3) Downcasting without the use of instanceof

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Animal{
     
}
 
class Dog extends Animal{
     
    static void method(Animal a){
            Dog d = (Dog)a;//down
    }
     
}
 
public class Test{
    public static void main(String[]args){
        Animal a = new Dog();
        Dog.method(a);
    }
}
 

'Back-End > Java_1' 카테고리의 다른 글

[Java] Interface  (0) 2016.09.12
[Java] Abstract class  (0) 2016.09.12
[Java] Static Binding and Dynamic Binding  (0) 2016.09.08
[Java] Runtime Polymorphism  (0) 2016.09.08
[Java] Final keyword  (0) 2016.09.07
블로그 이미지

리딩리드

,