1、多态存在的条件
- 有继承关系
- 子类重写父类的方法
- 父类引用 指向 子类对象
- 子类重写了父类的方法 则执行子类的方法
- 子类能调用自己的方法 和 继承父类的方法
- 父类只能调用和子类共有的方法,不能调用子类独有的方法
2、例子
public class Person {
public void run(){
System.out.println("I can run");
}
public void show(){
System.out.println("I am a person");
}
}
public class Student extends Person {
public void school() {
System.out.println("get to school");
}
@Override
public void show() {
System.out.println("I am a student");
}
}
public class Test {
public static void main(String[] args) {
Student stu = new Student();
//父类引用指向子类的对象
Person per = new Student();
//调用自己和父类的方法
stu.school();
stu.run();
stu.show();
//子类重写的方法
per.show();
//不能调用子类独有的方法
// per.school();
}
}
3、注意事项
- 多态是方法的多态 属性没有多态
- 需要有继承关系
- 方法需要重写
- 父类引用指向子类的对象 才行
- 有些方法无法重写
- static 修饰的
- final 修饰的
- private 修饰的
4、instanceof
用于判断两个类之间是否存在关系,判断一个对象是什么类型
public class Person {
public void run(){
System.out.println("I can run");
}
public void show(){
System.out.println("I am aperson");
}
}
public class Student extends Person {
public void school() {
System.out.println("get to school");
}
@Override
public void show() {
System.out.println("I am a student");
}
}
public class Teacher extends Person {
public void teach(){
}
}
public class Test {
public static void main(String[] args) {
Object object = new Student();
System.out.println(object instanceof Student); //true
System.out.println(object instanceof Person); //true
System.out.println(object instanceof Teacher);//false
Person person = new Student();
System.out.println(person instanceof Student); //True
System.out.println(person instanceof Person); //true
System.out.println(person instanceof Teacher); //false
System.out.println(person instanceof Object); //true
}
}
X instanceof y
- 可以编译通过 说明是存在关系 反之亦然
- true:是这个类型(父子关系)
- false:不是这个类型
5、类型转换
- 类型之间的转换 父子 ->( 高低)
- 父类的引用指向子类的对象
- 把子类转换为父类:向上转型
- 把父类转换为子类:向下转型
- 需要强制装换
- 这样就可以调用 子类独有的方法了
- 方便方法的调用 减少重复的代码
6、类型转换
- 类型之间的转换 父子 ->( 高低)
- 父类的引用指向子类的对象
- 把子类转换为父类:向上转型
- 把父类转换为子类:向下转型
- 需要强制装换
- 这样就可以调用 子类独有的方法了
- 方便方法的调用 减少重复的代码
- 抽象:封装,继承,多态,接口,抽象类