[Quote=引用 3 楼 zangxt 的回复:]
翻译没错,原书的问题。
Even though it doesn’t explicitly use the static keyword, the constructor is actually a static method. So the first time an object of type Dog is created, or the first time a static method or static field of class Dog is accessed, the Java interpreter must
locate Dog.class, which it does by searching through the classpath.
感觉前言不搭后语的。
看这本书要慎重,小心一些误导性的东东。
[/Quote]
看了一下原版英文,大概翻译是
即使没有显式的使用static关键字,构造器实际上也是静态方法。因此,第一次一个类型为Dog的对象被创建,或者第一次Dog类的静态方法或静态属性被访问时,java解释器就必须加载Dog.class,它是通过查找classpath而来的
所以感觉作者对static的理解是从类加载的角度上来考虑的,其实我们知道,一个类被使用到的时候,JVM就会加载该class,所以,即使不创建,也就是说没有new,只要引用到了该类,JVM应该就会自动加载class了,比如
Dog dog; //不需要Dog dog = new Dog();
或者
Class c = Dog.class;
等等,JVM都会查找classpath去加载Dog.class
所以个人感觉这段话有点问题,构造器是个特殊的方法,和new这个特殊操作符一起使用(new操作符会产生一个new指令),但是不至于是个static方法(就看对static怎么理解),可以通过反编译查看构造器的代码,第一步一般都是aload_0,也就是把this指针压栈,按照static的解释,static方法是不需要也不能直接访问这个this的。所以构造器是static的说法不成立。
我的理解:
构造器不是方法,不能用static修饰。它也不是变量,不能用一般的成员变量调用规则去对它套用。很特殊的存在。
《Thinking in Java》中说那句话,可能有如下原因:
1、中文翻译有误;
2、静态,作者可能理解为“属于类的”,构造器也确实属于类的,非某个对象的引用调用它;
3、构造器如果修饰为私有,如果别的类想创建该类的对象,必须使用静态工厂方法,这个静态工厂方法是……
[/Quote]
翻译没错,原书的问题。
Even though it doesn’t explicitly use the static keyword, the constructor is actually a static method. So the first time an object of type Dog is created, or the first time a static method or static field of class Dog is accessed, the Java interpreter must
locate Dog.class, which it does by searching through the classpath.
感觉前言不搭后语的。