(未编辑完,发布防丢
object-oriented design 面向对象三大特征
(1)Encapsulation 封装
(2)Inheritance 继承
(3)Polymorphism 多态
目录
Inheritance 继承
1. 继承基础
儿子继承爸爸
爸爸: super class / parent class 父类
儿子:sub class 子类
“is - a relationship"
子类继承了父类,但还有其他特点 【用图来表示,箭头指向的是superclass】
(一个parent class 可以有很多sub class,
但是在java中正常情况下一个sub class 只能有一个parent class)
Definition:
In object- oriented design, inheritance is a relationship between a more general class (superclass) and a more specialized class (subclass).
Function: reuse code instead of duplicating it
这种“reuse”有两种形式:
(1) a subclass inherits the methods of the superclass
(2) reuse algorithms that manipulate the objects -- substitution principle
you can always use a subclass object when a superclass object is expexted
2. 继承方法
extends 创建
class superclass{
// constructor
// 代码段
}
class subclass extends superclass{
// constructor
// 代码段
}
the subclass inherits all public methods from the superclass 继承的时候直接继承public的内容
private不能直接这样继承,需要隐形访问(AP不考
3. overloading & overriding
Override
When you supply a new implementation for an inferited method, you override the method
子类改变父类的东西
overloading:
two methods can have the same name, provided they differ in their parameter types
different methods, with its own implementation, java compiler: completely unrealted
3. this 的用法
对调用对象的引用
this radius = radius;
4. super 的用法
function:
calls the method of the superclass
如果子类想要访问父类中的同名变量,用super来进行引用
指代 superclass, 用于强调父类中的 normal method 和 constructors(构造方法)
在java 中如果没有使用super程序会自动补,因为子类继承父类的所有东西
无参调用
如果没有写,程序会自动留下:
super ();
constructor chaining 方法链:
调用父类,如果没有父类调用父类的父类
为了避免问题,一般情况下最好能为每个class类提供一个无参构造方法,以便于对该class类进行继承
//无参构造器
radius () {
}
super 对于 normal method 的调用
getDateCreated 在父类中出现了,但不在子类中
这种情况下可以写 getDateCreated ()或者是 super.getDateCreated()
6. upcasting & downcasting
[ 图片来源:bing ]
upcasting:
parent class references point to subclass object
向上转型:父类引用指向子类对象
Father David = new Son();
//在此处假设father是父类,son是子类
* 向上转型的过程中,如果父类没有该object,此子类的object会消失掉
好处:
1. 减少重复代码
2. 提高代码扩展性
坏处:
1. upcasting 后, subclass 子类单独定义的method方法会丢失
Polymorphism 多态
例如“cut”这个object可能代指很多不同的含义,这就是多态的一种含义
可以通过转型来运行不同的结果