对应第4章
1、主类型的过载
类型排序:char、byte、short、int、long、float、double
对于某一类型,可以用比它高级点的类型存储。例如byte可以用byte、short、int、long、float、double存储,每次总是自动选择最合适(不浪费)的类型来存储,比如byte如果不可以用byte传递,就会找short存储。
char比较特殊,只能用char、int、long、float、double存储
2、对象初始化
原则:
对于类对象new时总是先执行属性语句后执行构造函数;
static的属性或方法仅执行一次;
static的东西先执行(明白了为啥main函数一般都先执行,因为是static的);
static的属性和static的方法还是属性先执行;
static的东西是属于整个类的
例子:
StaticInitialization.java
package initialization;
//: initialization/StaticInitialization.java
// Specifying initial values in a class definition.
import static net.mindview.util.Print.*;
class Bowl {
Bowl(int marker) {
print("Bowl(" + marker + ")");
}
void f1(int marker) {
print("f1(" + marker + ")");
}
}
class Table {
static Bowl bowl1 = new Bowl(1);
Table() {
print("Table()");
bowl2.f1(1);
}
void f2(int marker) {
print("f2(" + marker + ")");
}
static Bowl bowl2 = new Bowl(2);
}
class Cupboard {
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard() {
print("Cupboard()");
bowl4.f1(2);
}
void f3(int marker) {
print("f3(" + marker + ")");
}
static Bowl bowl5 = new Bowl(5);
}
public class StaticInitialization {
public static void main(String[] args) {
print("Creating new Cupboard() in main");
new Cupboard();
print("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
} /* Output:
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)
*///:~
注意:在StaticInitialization类中,先执行最后的两个属性语句,后才执行main方法,这就是先属性后方法的应用。而static的东西仅初始化一次。
与一般的直接从main开始执行有差别
第四章练习题暂未看。