多态
- 多态编译:类型 :可拓展化
- 即同一方法可以根据发送对象的不同而采用多种不同的行为方式
- 一个对象的实际类型是确定的,但是可以指向对象的引用的类型很多
多态存在的条件
-
有继承关系
-
子类重写父类的方法
-
父类引用指向子类对象
注意 :多态是方法的多态,属性没有多态性
-
多态是方法的多态,属性是没有多态
-
父类和子类是继承关系,有联系 ! ClassCastExcepetion;
-
存在条件:继承关系,方法需要重写 ,父类引用指向子类对象! Father f1 = new Son();
但是有些方法不能杯重写
- static 是静态方法,属于类,不属于实例
- final 常量
- private 私有的也不能
-
(s1有run,s2有run,两个都有run,程序是只有在运行的时候才知道调用谁)
对我们来说看左边哪个类的就执行哪里的,两个类型都有的时候就只执行子类的。
Application
package com.oop;
import com.oop.Demo05.Person1;
import com.oop.Demo05.Stunden1;
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
//类型之间的转换 父亲 儿子
//高 低 低转高 向上转型自动升型,
Person1 p1 = new Stunden1();
//s1将这个对象转换为Student类型,我们就可以使用Student1类型的方法
// 低 s1为高 高到低 向下转型 强制
Stunden1 s1 = (Stunden1)p1;//强制转换
s1.go();
p1.move(); //还是输出子类的重写方法,丢失父类的原始方法
//((Stunden1)s1).go(); 也可以这样写之间强制加调用
//同级的子类之间不能强制转换
// Teacher t1 = (Stunden1)s1; 编译不通过s1已经被转换为tudent1S,
Stunden1 s2 = new Stunden1();//可以调用本身的方法
s2.go();;
}
/*
1.父类引用指向子类的对象
2.把子类转换为父类,向上转型,自动转型,丢失子类中原本可以之间调用的特有方法
3.父类转换为子类要强制转换,向下转型,丢失父类被子类所重写的方法。
4.方便方法的调用,减少重复的代码
抽象 : 封装,继承,多态
*/
}
Person1
package com.oop.Demo05;
public class Person1 {
public void move(){
System.out.println("移动");
}
}
/*
//Object > String
//Object > Person1 > Teacher
//Objiec > Person1 >Student1
Object object = new Stunden1();
//System.out.println(X instanceof Y);//判断是否编译通过
System.out.println(object instanceof Stunden1);//ture
System.out.println(object instanceof Person1);//ture
System.out.println(object instanceof Object);//ture
System.out.println(object instanceof Teacher);//false
// Object > Person1 > Teacher 没有在Student1里面所有false,兄弟不能跟父子一样
System.out.println(object instanceof String);//false
//Object > String String跟Person1属于同类也不知Student1里面
Person1 person = new Stunden1();
System.out.println("================================");
System.out.println(person instanceof Stunden1);//ture
System.out.println(person instanceof Person1);//ture
System.out.println(person instanceof Object);//ture
System.out.println(person instanceof Teacher);//false
// System.out.println(person1 instanceof String);//编译报错
Stunden1 stunden1 = new Stunden1();
System.out.println("================================");
System.out.println(stunden1 instanceof Stunden1);//ture
System.out.println(stunden1 instanceof Person1);//ture
System.out.println(stunden1 instanceof Object);//ture
//System.out.println(stunden1 instanceof Teacher);//编译报错
// System.out.println(stunden1 instanceof String);//编译报错
*/
Student1
package com.oop.Demo05;
public class Stunden1 extends Person1 {
public void go(){
System.out.println("go");
}
@Override
public void move() {
System.out.println("学生跑了起来");
}
}
Teacher
package com.oop.Demo05;
public class Teacher extends Person1 {
}