final关键字类似const:

 import java.util.*;

 public class FinalData {
static Random rand = new Random(47);
final int valueOne = 9;
final int i4 = rand.nextInt(20);
static final int INT_5 = rand.nextInt(20);
public static void main(String[] args) {
FinalData f = new FinalData();
//f.valueOne = 7;
//f.i4 = 7;
System.out.println(f); FinalData f1 = new FinalData();
System.out.println(f1);
}
public String toString() {
return
"valueOne = " + valueOne
+ " " + "i4 = " + i4
+ " " + "INT_5 = " + INT_5;
}
}

注意到:i4和INT_5的差别:类的不同对象中INT_5只在地一个对象创建的时候初始化一次,而i4则在每个对象创建的时候初始化一次。

关于名字屏蔽和C++的原则是不同的

C++中子类的重载函数会屏蔽掉基类中的其他函数:

 #include <iostream>

 class Homer {
public:
char doh(char c) {
std::cout << "doh(char)" << std::endl;
return 'd';
} float doh(float f) {
std::cout << "doh(float)" << std::endl;
return 1.0f;
}
}; class Milhouse {}; class Bart : Homer {
public:
void doh(Milhouse& m) {
std::cout << "doh(Milhouse)" << std::endl;
}
}; int main() {
Bart b;
//b.doh(1);
b.doh('x');
//b.doh(1.0f);
Milhouse m;
b.doh(m);
return ;
}

而java不会

 class Homer {
char doh(char c) {
System.out.println("doh(char)");
return 'd';
} float doh(float f) {
System.out.println("doh(float)");
return 1.0f;
}
} class Milhouse {} class Bart extends Homer {
void doh(Milhouse m) {
System.out.println("doh(Milhouse)");
} @Override char doh(char c) {
System.out.println("Bart:doh(char)");
return 'c';
}
} public class Hide {
public static void main(String[] args) {
Bart b = new Bart();
b.doh(1);
b.doh('x');
b.doh(1.0f);
b.doh(new Milhouse());
}
}

还有就是要注意初始化顺序

 class Insect {
Insect() {
System.out.println("Insect::Insect()");
} static int i = printInit("static Insect::i"); static int printInit(String s) {
System.out.println(s);
return 5;
} int j = printInit("Insect::j");
} public class Beetle extends Insect {
Beetle() {
System.out.println("Beetle::Beetle()");
} public static void main(String[] args) {
System.out.println("Beetle::main()");
new Beetle();
} int k = printInit("Beetle::k");
static int l = printInit("static Beetle::l");
}
05-25 20:52