package com.mypackage.oop.demo08;
public class Person08 {
public void run(){
System.out.println("run");
}
}
/*
多态注意事项:
1.多态是方法的多态,属性没有多态
2.父类和子类之间才能强制转换,否则会有类型转换异常 ClassCastException
3.存在条件:继承关系,父类引用指向子类对象
不可重写的方法:
1.static 静态方法 属于类 不属于实例
2.final 常量
3.private 私有
*/
package com.mypackage.oop.demo08;
public class Student08 extends Person08 {
@Override
public void run(){
System.out.println("son");
}
public void eat(){
System.out.println("eat");
}
}
package com.mypackage.oop.demo08;
public class Application08 {
public static void main(String[] args) {
//一个对象的实际类型是确定的
new Student08();
new Person08();
//但对象可以指向的引用类型就不确定了
Student08 s1 = new Student08();
Person08 s2 = new Student08(); //父类的引用指向子类的类型
Object s3 = new Student08();
Person08 p1 = new Person08(); //父类的引用指向自己
//对象能执行哪些方法,主要看的是等号左边的类型
s2.run(); //son
//s2.eat(); //会报错
//父类虽然可以指向子类,但是不能调用子类独有的方法
((Student08)s2).eat(); //进行强制性转换,高转低(父转子)(不能同级之间进行类型转换) //eat
s1.eat(); //eat
s1.run(); //son
p1.run(); //run
}
}
用于判断一个对象是什么类型,判断两个对象是否具有父子关系
package com.mypackage.oop.demo09;
public class Application09 {
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); //编译即报错,因为Person和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); //编译即报错,因为Student和Teacher是无继承关系的
//System.out.println(person instanceof String); //编译即报错,因为Student和String是无继承关系的
System.out.println("================");
Object object2 = new Person();
System.out.println(object2 instanceof Student); //false 因为person比student大
System.out.println(object2 instanceof Person); //true
System.out.println(object2 instanceof Object); //true
System.out.println(object2 instanceof Teacher); //false 因为person比teacher大
System.out.println(object2 instanceof String); //false
//只要等号左边的类型没有父子关系,就会编译错误
//等号左边的类型有父子关系,右边的类型无父子关系或者父在instanceof前,就会输出false
/*
类型之间的转换:
基本类型的转换 类型的高低
父 子 : 强制转换方式与基本类型的强制转换方式一样,前面加个括号写上要转换成的类型
父类转为子类没什么影响,因为基本上父类的方法子类都有。但子类转换为父类可能会丢失一些子类本有的方法
*/
//父类引用可以指向子类,子类引用不可以指向父类
}
}