也有 this
implicit parameter
Be Careful to Return Mutable Objects
这是说,当你的 class 中用到了别的 class 作为 data,那么当写其对应的 accessor 时,要注意:
- 如果这个“别的 class”是一个 immutable class, which means there is no mutator method,那你可以直接 return (并不妨碍指向同一个地方)
- 如果这个“别的 class”是一个mutable class,那要 clone 出来 return
其中的关键点就是,虽然这个 data 是 private 的,但是当你 new 一个新的 obj variable 时,他们指向的是同一块区域
private 限制了通过 obj 直接改变 data,但是对于这种“间接”的行为,是没办法的
Principle
为什么要酱紫强调?因为我们使用 private 的目的就是 encapsulation,而以上的行为破坏了 encapsulation
Method Parameters
跟 C++ 说的差不多,都有 call by value/reference,而且都是 init local variable with para
Java Still Uses Call by Value for Objects
由于 object variable is analogous to object pointer。所以如果直接传值,没错,确实传的值,只不过传的是 reference,那效果都是生效的。并且方法结束后,local object method 确实没了
在 C++ 中也得到验证了的,因为只是 local 指向的东西变了一下
当我们在 C++ 中说 reference 的时候,我们强调的是它本身,但我们在 Java 中说 reference 的时候,我们更像是在描述 pointer
Mutator and Accessor Methods
就是一个方法会不会修改这个 obj
ℹ️ C++ 中 method 有 const
来表明这是一个 Accessor,但是 Java 中没有
Static Fields and Methods
看起来 Java 中的静态东西玩法要比 C++ 中要自由很多,很多很多。感觉真的就是所谓的静态而已
If you define a field as static
, then there is only one such field per class.
What the Heck Meaning of
static
?The term “static” is a meaningless holdover from C++. 这中间是有故事的,其实最开始是好理解的,中间经过了两次词义扩张,才使得这个意思越变越怪
所以就把“static fields”理解为“class fields”吧,和“instance fields”对比起来
其实 System.out
就是一个 static constant
How to Define a Static Field
一个 static method 表明他没有 this para,不对 obj 做操作,当满足以下条件时,我们倾向用它:
- When a method doesn’t need to access the object state because all needed parameters are supplied as explicit parameters (example: Math.pow).
- When a method only needs to access static fields of the class (example: Employee.getNextId).
Factory Methods
这是静态方法的一个应用,我们使用工厂方法的原因通常是:
- 因为构造方法没法命名,有的时候我们又要区分开来,所以可以用工厂方法,因为工厂方法可以有不同的名字
- When you use a constructor, you can’t vary the type of the constructed object. But the factory methods actually return objects of the class DecimalFormat, a subclass that inherits from NumberFormat. (See Chapter 5 for more on inheritance.)
没看懂
The main
Method
Every class can have a main
method. That is a handy trick for unit testing of classes.
由于被执行的主程序被要求与类与文件名相同,所以不用担心测试 main
方法被错误的调用
Final Methods
Understanding Method Calls
Methods with a Variable Number of Parameters
public class PrintStream {
public PrintStream printf(String fmt, Object... args) {
return format(fmt, args);
}
}
...
来表示可变长,其实实际上就是一个 Object[]
System.out.printf("%d %s", new Object[] { new Integer(n), "widgets" } );
上述写法不光是形式上等价,实际上真的可以这么调用