instanceof 和类型转换
注意点
-
-
把子类转换为父类,向上转型;
-
把父类转换为子类,向下转型;强制转换
-
方便方法的调用,减少重复的代码!简洁
封装、继承、多态! 抽象类,接口
快捷键
补充语句
举例
转换类型之后使用方法
输出结果
这样改写,输出结果一样
代码
//Java-零基础学习/src/oop/demo06/Student
package oop.demo06;
public class Student extends Person {
public void go() {
System.out.println("go");
}
}
/*
public static void main(String[] args) {
//一个对象的实际类型是确定的
//new Student();
//new Person();
//可以指向的引用类型就不确定了:父类的引用指向子类
//Student 能调用的方法都是自己的或者继承父类的!
Student s1 = new Student();
//Person 父类型,可以指向子类,但是不能调用子类独有的方法
Person s2 = new Student();
Object s3 = new Student();
//对象能执行哪些方法,主要看对象左边的类型,和右边关系不大!
s2.eat();//子类重写了父类的方法,执行子类的方法
s1.eat();
}
*/
/*
public static void main(String[] args) {
//Object > String
//Object > Person > Teacher
//Object > Person > Student
Object object = new Student();
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false
System.out.println("=================================");
Person person = new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false
//System.out.println(person instanceof String);//编译报错!
System.out.println("=================================");
Student student = new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);//编译报错!
//System.out.println(person instanceof String);//编译报错!
}
*/
//Java-零基础学习/src/oop/demo06/Person
package oop.demo06;
public class Person {
public void run() {
System.out.println("run");
}
}
/*
public static void main(String[] args) {
//类型之间的转化:父 子
//高 低
Person obj = new Student();
//student将这个对象转换为Student类型,我们就可以使用Student类型的方法了!
Student student = (Student) obj;
student.go();
}
*/
/*
public static void main(String[] args) {
//类型之间的转化:父 子
//子类转换为父类,可能丢失自己的本来的一些方法!
Student student = new Student();
student.go();
Person person = student;
}
*/
//Java-零基础学习/src/oop/demo06/Teacher
package oop.demo06;
public class Teacher extends Person {
}
//Java-零基础学习/src/oop/Application
package oop;
import oop.demo06.Person;
import oop.demo06.Student;
import oop.demo06.Teacher;
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[] args) {
//类型之间的转化:父 子
//子类转换为父类,可能丢失自己的本来的一些方法!
Student student = new Student();
student.go();
Person person = student;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现