Head First Java 笔记2

2020-02-03  本文已影响0人  Wilbur_

在写代码之前一般都要写一下自己的想法,书里就叫做prep code。 是为了把自己的框架列出来,然后能够清晰的把每个object和他们的method写出来,以及清楚看到他们之间的关系。

battleship 这个游戏主要有三个object,一个是DotComBust,它是为了生成(开始)游戏,建立helper method,还有ArrayList(存放各个DotCom名字还有他们位置的object。
如下图所示:


HeadFirst Java 142-143

Make it stick

反思之所以重要就是因为它能够让一个比较有效的方法深刻的印在你的脑子里,然后发挥原本比他更重要的作用。所以说闭环跟重复再加上时间是会有非常神奇的效应的。

Inheritance (61b里面学过的)
When you design with inheritance, you put common code in a class and then tell other more specific classes that the common (more abstract) claass is their superclass. When one class inherits from another, the subclass inherits from the superclass.
An inheritance relation ship means that the subclass inherits in herits the members of the superclass. When we say "nenbers of a class" we mean the instance variables and methods.
we mean the sinstance variables and methods.
For example, if PantherMan is a subclass of uperhero, the pantherman calss automatically inhertis the instance variables and methods common to all superheroes including suit.,
tights, special Power, useSpecialPower and so on. But the pantherMan subclass can add new methods and instance variables of its own, and it can override the methods it inherits from the superclass SuperHero.
Instance variables are not overridden because they don't need to be. They don't define any special behavior, so a subclass can give an inherited instance variable any value it chooses. PantherMan can set his inherited tights to purple, while FriedEggMan sets his to white.

IS-A test

当你怀疑一个class 是否inheritance另一个class的时候,你需要apply IS-A test。 这样能够更清楚的帮你了解需不需要inheritance。 比如cat IS-A feline, 这是对的。 Tub is-a bathroom,这就不对了,所以Tub不能inheritance bathroom,那tub 和bathroom的关系是什么呢? 是Has-A, Bathroom has a tub. 所以tub只是bathroom里面一个instance variable。不要搞混他们,不然就会出错。

Subclass

The thing that stops a class from being subclassed is the keyword modifier final. A final class means that it's the end of the inheritance line. Nobody, ever, can extend a final class.

The third issue is that if a class has only private constructors, it can't be subclassed.

Overloading a method

Overloading a method is nothing more than having two methods with the same name but different argument lists. Period.
The return types can be different. You can't change ONLY the return type.
An overloaded mthod is just a different method that happens to have the same method name. it has nothing to do with inheritance and polymorphism. An overloaded method is NOT the same as an overridden method.

上一篇下一篇

猜你喜欢

热点阅读