封装详见:Java的三大特性之封装
继承详见:Java的三大特性之继承
多态介绍
可实现动态编译,可扩展性
即同一个方法可以根据发送对象的不同而采取不同的行为方式。
一个对象的实际类型是可以确定的,但可以指向对象的引用类型有很多(父类 / 有关系的类)。
详看注释↓↓↓
注意点
- 多态是方法的多态,属性没有多态性;
- 父类和子类,有联系,类型不匹配则转换异常(ClassCastException);
- 存在条件:继承关系;方法重写;父类引用指向子类对象。
- static 方法,属于类,不属于实例
- final 常量
- private 方法
附加:instanceof和类型转换
instanceof (类型转换) 引用类型 判断对象是一个什么类型。
1.先用 instanceof 判断两个类之间是否存在父子关系:
public class Demo1 {
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); //编译报错
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); //编译报错
//System.out.println(student instanceof String); //编译报错
}
}
2.高转低(强制转换)
子类转换为父类,可能会丢失自己本来的一些方法。
总结
- 父类的引用指向子类的对象
- 把子类转换为父类,向上转型,直接转
- 把父类转换为子类,向下转型,强制转换
- 方便方法的调用,减少重复的方法
要多理解!
感谢ლ(°◕‵ƹ′◕ლ)!!!