栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java学习之运算符instanceof使用场景

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java学习之运算符instanceof使用场景

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
//Triangle triangle =(Triangle)s  //向下转型抛出运行时异常
//triangle.drawTri();
        
   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();
   }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/345938.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号