动态编译:类型:可扩展性
即同一个方法可以根据发送对象的不同而采取多种不同的行为方式
一个对象的实际类型是确定的,但可以指向对象的引用类型有很多
多态存在的条件
-
有继承关系
-
子类重写父类方法
-
父类引用指向子类
注意
多态是方法的多态,属性没有多态性
异常
类型转换异常:ClassCastException
不能重写的
-
static方法,属于类,不属于实例
-
final 常量
-
private方法
主方法
public class example {
public static void main(String[] args){
//一个对象的实际类型是确定的的
//可以指向的引用类型就不确定了
//父类的引用指向子类
//Student能调用的方法都是自己的或者继承父类的
Student s1 = new Student();
//父类可以指向紫烈,但是不能调用子类独有的方法
Person s2 = new Student();
Object s3 = new Student();
s2.run();
s1.run();
s1.eat();
((Student)s2).eat();//强转!!!
}
}
父类
public class Person {
public void run(){
System.out.println("run");
}
}
子类
public class Student extends Person{
关键字
instanceof
要求对象的两个类要有包含关系,才不报错。
public class example {
public static void main(String[] args) {
//Object > String
//Object > Person > Teacher
//Object > Person > Student
//System.out.println(X instanceof Y);//能不能编译通过
//有父子关系则通过
Object object = new Student();
System.out.println(object instanceof Student);//ture
System.out.println(object instanceof Person);//ture
System.out.println(object instanceof Object);//ture
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);//ture
System.out.println(person instanceof Person);//ture
System.out.println(person instanceof Object);//ture
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);//ture
System.out.println(student instanceof Person);//ture
System.out.println(student instanceof Object);//ture
//System.out.println(student instanceof Teacher);//编译报错
//System.out.println(student instanceof String);//编译报错
}
}
子类转换为父类,可能丢失自己本来的一些方法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~