Java学习之运算符instanceof使用场景
1.意义
instanceof是二元运算符,用于判断对象是否为特定类的实例。
2.用法
boolean result = object instanceof class
3.举例分析
class Uncle{}
class Pare{}
class Pare1 extends Pare{}
class Pare2 extends Pare1{}
class Pare3 {
public static void main(String[] args){
Uncle u = new Uncle();
Pare p = new Pare();
Pare1 p1 = new Pare1();
Pare2 p2 = new Pare2();
if ( p instanceof Pare)
{System.out.println("p instanceof Pare");}
if (!( p1 instanceof Pare))
{System.out.println("p1 not instanceof Pare");}
else
{System.out.println("p1 instanceof Pare");}
if (p1 instanceof Pare2)
{System.out.println("p1 instanceof Pare2");}
else
{System.out.println("p1 not instanceof Pare2");}
if (null instanceof String)
{System.out.println("null instanceof String");} else
{System.out.println("null not instanceof String");}
Shape s = new Rect(10,30);
s = new Triangle(5,5,8);
s = new Circle(12.5);
java.lang.ClassCastException: Circle cannot be cast to Triangle
if(s instanceof Rect){
Rect rectangle = (Rect)s;
rectangle.drawRect();
} else if (s instanceof Triangle){
Triangle triangle =(Triangle)s;
triangle.drawTri();
} else if (s instanceof Circle){
Circle circle = (Circle) s;
circle.drawCir();
}
|