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
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
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
Dog d =
new
AnImal();
//Compilation error
Dog d = (Dog)
new
Animal()
// ClassCastException
2) Possibility of downcasting with instanceof
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
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 |