活跃农民
- 积分
- 997
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-4-19
- 最后登录
- 1970-1-1
|
记录了一下今天的工作时间,有效利用的时间只有8个小时, 9: 30 - 11: 30 am, 1: 30 - 2: 30 pm, 3:10 - 5: 25 pm, 6:50 - 9 :50pm, 特别是一个早上只工作了俩小时。。。平时如果不做记录的话,工作时间还达不到这样。。。不记录一下都不知道自己浪费了多少时间,所以以后刷题帖还是要尽量日更。
今天上午读了Java Docs Inheritance 相关的内容,总结如下:
(1) Java 不支持Multiple Inheritance,也就是说一个subclass只能有一个direct superclass (Object 除外,Object没有superclass),一个原因是为了要避免Multiple Inheritance of states issues, 因为class 是有instance variable的,如果支持Multiple inheritance的话,多个superclass可能有相同的instance variable, 这样compiler无法辨别应该使用哪一个。
(2) 一个subclass可以implements多个interface, interface 没有 instance variable, 所以不存在上述问题。
(3) 既然一个class一个extend一个superclass, 同时implements多个interface, 如果这些superclass和interface当中有多个具有同样signature的method, compiler如何选择:
* Compiler 会跟根据inheritance rule来做选择:
* superclass 的instance method比interface 的default method 优先级更高 (第一次知道interface 也是可以有implemented method 的)
* 已经被override的method不予考虑
* 在这两个规则之下,如果还有多个methods具有相同的signature,那么compiler报错
(4)subclass 继承superclass当中所有的public, protected, package-private fields 和methods。superclass 的 private fields 不能被继承,但是如果superclass中有public method可以access这些private fields, 那么这些fields也可以被subclass使用。
(5)subclass 不继承superclass的constructor, 只能invoke, 用法是super(…), 如果sublass 的constructor 没有explicitly地调用super(…), compiler会自动插入一个non-arg super constructor, 也就是super(), 此时,如果superclass里没有 non-arg constructor,compiler 就会报错
(6)Abstract class 和 interface 的异同
* 同: 都不能被instantiate, 都包含有一系列methods (with or without implementation)
* 异:
* interface 的fields自动被设置为public static final, 而abstract class是能够有non-static, non-final fields的
* Interface 只能declare public method, abstract class 能够包含各种access level 的methods
* 啥时候用abstract class,啥时候用interface
* 当应用这个superclass 或者interface的classes是一系列紧密相关的classes,需要share很多同样的fields的时候,考虑abstract class,比如说,如果你的classes 是 MountainBike 和RoadBike, 那么把Bike设置成abstract class就比较好,因为MountainBike和RoadBike有很多部件(fields)都是相同的。
* 相反当应用这个superclass 或者interface的Classes是unrelated的时候, 比如说很多的类都需要能够compare,clone, 或者serialize, 那么Comparabe(), Clonable(), Serializable()这些就应该设置成interface
* 当然superclass 只能有一个,interface能够有多个,也是很重要的考量方向。
下午在做一个OODesign的practice: ChessGame design:
看到一个很好的视频:https://www.youtube.com/watch?v=h8fSdSUKttk |
|