当前位置: 首页 > news >正文

instanceof和类型转换

instanceof和类型转换

instanceof判断具体实例与类对象的关系

package Demo01;public class Person {}
package Demo01;public class Student extends Person{}
package Demo01;public class Application {public static void main(String[] args) {//Object->String//Object->Person->StudentObject student = new Student();System.out.println(student instanceof Student);System.out.println(student instanceof Person);System.out.println(student instanceof Object);System.out.println(student instanceof String);System.out.println( );Student student1 = new Student();System.out.println(student1 instanceof Student);System.out.println(student1 instanceof Person);System.out.println(student1 instanceof Object);//System.out.println(student1 instanceof String);System.out.println( );Person student2 = new Student();System.out.println(student2 instanceof Student);System.out.println(student2 instanceof Person);System.out.println(student2 instanceof Object);//System.out.println(student2 instanceof String);//System.out.println(x instanceof Y);判断x和Y有没有继承关系//具体实例与实际类型的父子类的instanceof为true//具体实例与引用类型的父子类的instanceof为false}
}

输出结果为:

true
true
true
false

true
true
true

true
true
true


类型转换

  1. 父类引用指向子类的对象
  2. 把子类转换为父类,向上转型
  3. 把父类转换为子类,向下转型;强制转换
  4. 方便方法的调用,减少代码的重复性,更简洁。
package Demo01;public class Person {}
package Demo01;public class Student extends Person{
public void test(){System.out.println("测试");
}}
package Demo01;public class Application {public static void main(String[] args) {//Student为Object的子类 由低转高Object a = new Student();//a.test()无法使用Student的方法因为不是Student类型//将a对象转换成Student类型,使用其方法Student a1 = (Student) a;a1.test();Student student1 = new Student();Person person=student1;//person.test();//子类转成父类,会丢失原本自己子类的方法}
}

输出结果为:

测试

http://www.dtcms.com/a/496357.html

相关文章:

  • MySQL 企业版数据脱敏与去标识化
  • 物流信息网站wordpress下载样式
  • 网站建设与维护要用到代码吗网站实用性
  • 常州住房和城乡建设部网站北京建设集团网站
  • 正规的GEO优化师培训哪家好
  • 建设银行甘肃省行网站wordpress请求接口的方式
  • 怎么开网站做网红淮安网站建设公司
  • 昌平建设网站徐州seo推广优化
  • 国内旅行做行程网站网站建设公司怎么谈单
  • vscode制作个人网站做爰片免费观看网站
  • 教育网站 网页赏析找公司做网站要注意什么问题
  • 卷积神经网络(CNN)入门实践及Sequential 容器封装
  • 高端网站建设 磐石网络专注自己的服务器建网站
  • 普陀建设网站wordpress开启全站ssl
  • 近期的笔试和面试的复盘
  • 公司邮箱免费注册seo营销培训咨询
  • 从控制到执行:理解 MCP Server 与 Agent 的关系
  • 学做网站网自己的代码放WordPress
  • 创建蛋糕网站建设方案开发网站心得
  • 2025 GEO 在线优化服务商有哪些?这几款各有侧重,哪家好?
  • 取消cine camera的预览窗口
  • public,private与protected
  • 【题解】B2614【深基1.习6】鸡兔共笼
  • 网站 默认首页深圳flash网站建设
  • 网站虚拟空间多少钱用糖做的网站
  • 域名绑定了ip地址,也安装了宝塔但还是无法访问
  • python+vue电动汽车智能充电管理系统
  • 网站开发费属于无形资产深圳制作网站
  • 探域科技在AI电商应用深度调研报告(2025年更新版)
  • 建网站语言深圳室内设计师网