面向对象思想------封装
-
该show的show,该hide的hide
- 我们程序设计要尽量保证“高内聚,低耦合”,高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用。
-
封装(Data hiding)
- 通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏。
-
封装的本质
- 属性私有(private,数据隐藏),getter/setter(get方法和set方法,数据显露)
-
封装的实际作用
- 提高程序的安全性,保护数据
- 隐藏代码的实现细节
- 统一接口
- 系统可维护增加了
面向对象思想------继承
-
继承的本质是对某一批类的抽象,从而实现对现实世界更好的建模
-
extends 的意思是扩展,子类是父类的扩展
-
java中类只有单继承,没有多继承!
-
被final关键字修饰的类不能被继承
-
继承是类和类之间的一种关系,除此之外,类和类之间的关系还有依赖、组合、聚合等。
-
继承关系的两个类,一个为子类(派生类),一个为父类(基类)。子类继承父类,使用关键字extends来表示
-
子类和父类之间,从意义上讲应该具有“is a”的关系。
-
Object是所有类的基类
-
super详解
- super调用父类的构造方法,必须在构造方法的第一个
- super必须只能出现在子类的方法或构造方法中!
- super和this不能同时调用构造方法!
-
super VS this
- 代表的对象不同:
- this:本身调用者这个对象
- super:代表父类对象的引用
- 前提不同
- this:没有继承也可以使用
- super:只能在继承条件下才可以使用
- 代表的构造方法不同
- 本类的构造方法
- 父类的构造方法
- 代表的对象不同:
-
方法的重写
- 需要有继承关系,子类重写父类的方法
- 方法名必须相同(方法体不同)
- 参数列表必须相同
- 修饰符:范围可以扩大但不能缩小:public>protected>default>private
- 抛出的异常:范围可以被缩小,但不能扩大;ClassNotFoundException(小) —> Exception(大)
-
为什么要重写
- 父类的功能,子类不一定需要,或者不一定满足
- 快捷键:Alt + Insert -----> OVERRIDE
面向对象思想------多态
-
即同一方法可以根据发送对象的不同而采用多种不同的行为方式
-
一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多(父类,有关系的类)
-
多态存在的条件
- 有继承关系
- 子类重写父类方法
- 父类引用指向子类对象 (Father f1 = new Son();)
- 多态是方法的多态,属性没有多态性
-
instanceof详解
public class Application { public static void main(String[] args) { //instance of 判断2对象之间是否存在父子关系 //Object > String //Object > Person > Teacher //Object > Person > Student Object object = new Student(); System.out.println(object instanceof Object);//true System.out.println(object instanceof Student);//true System.out.println(object instanceof Person);//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 Object);//true 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 String); 编译错误 System.out.println("================="); Student student = new Student(); System.out.println(student instanceof Object);//true System.out.println(student instanceof Student);//true System.out.println(student instanceof Person);//true // System.out.println(student instanceof Teacher);编译错误 // System.out.println(person instanceof String);编译错误 } }
-
类型转换
- 父类引用指向子类的对象
- 把子类转化为父类,向上转型 (可能丢失自己的本来一些方法)
- 把父类转换为子类,向下转型(强制转换)
- 类型转换的作用:方便方法的调用,减少重复的代码