一、多态
主要包含测试文件、父类文件Person1、子类文件Teacher1
//Application
package com.MA;
import com.MA.operator.demo3duotai.Person1;
import com.MA.operator.demo3duotai.Teacher1;
public class Application {
public static void main(String[] args) {
Teacher1 t1 = new Teacher1();//正常new
Person1 t2 = new Teacher1(); //父类引用指向子类
Object t3 = new Teacher1(); //object也行
t2.run();//父类定义子类
t1.run();//子类重写父类里的方法
t1.eat();
((Teacher1)t2).eat(); //向下转换 相当于强制性int小数点
}
}
//Person1
package com.MA.operator.demo3duotai;
public class Person1 {
public void run(){
System.out.println("run");
}
}
//Teacher1
package com.MA.operator.demo3duotai;
public class Teacher1 extends Person1{
@Override
public void run() {
System.out.println("儿子就要jump");
}
public void eat(){
System.out.println("eat");
}
}
这里通过override重写了父类的方法,看一下Application里的输出:
儿子就要jump
儿子就要jump
eat
eat
如果只是t2.eat()会报错因为子类中有方法而父类中没有该方法,这是需要一下代码进行强制转换
((Teacher1)t2).eat(); //向下转换 相当于强制性int小数点
二、Instanceof
//instanceof 用来进行判断类型是否相似
//System.out.println(X instanceof Y); //判断XY的关系
//Object -> Person1 -> Teacher1
//Person1 -> Teacher1
//Object -> String
Object object = new Teacher1();
System.out.println(object instanceof Teacher1);
System.out.println(object instanceof Person1);
System.out.println(object instanceof Object);
System.out.println(object instanceof String); //不是父子关系
System.out.println("*********************************");
Person1 person1 = new Teacher1();
System.out.println(person1 instanceof Teacher1);
System.out.println(person1 instanceof Person1);
System.out.println(person1 instanceof Object);
// System.out.println(person1 instanceof String); //编译就报错 Person和String都是同级关系他们无法比较
Teacher1 teacher1 = new Teacher1();
System.out.println(teacher1 instanceof Teacher1);
System.out.println(teacher1 instanceof Person1);
System.out.println(teacher1 instanceof Object);
// System.out.println(person1 instanceof String); //同样如果父类下同样设置Student也会报错
输出结果
true
true
true
false
*********************************
true
true
true
true
true
true
三、强制转换
public class Application {
public static void main(String[] args, Teacher1 teacher1) {
//类型转换:父 子 直接转换
Person1 teacher12 = new Teacher1();
//能创建类别但是无法使用子类中的eat方法
// teacher12.eat(); 编辑报错
//强制转换 就可以使用子类中的eat方法
Teacher1 Tidai = (Teacher1) teacher12;
Tidai.eat();
//想用子类的方法还可以
((Teacher1)teacher12).eat();
}
}