final关键字类似const:
1 import java.util.*; 2 3 public class FinalData { 4 static Random rand = new Random(47); 5 final int valueOne = 9; 6 final int i4 = rand.nextInt(20); 7 static final int INT_5 = rand.nextInt(20); 8 public static void main(String[] args) { 9 FinalData f = new FinalData(); 10 //f.valueOne = 7; 11 //f.i4 = 7; 12 System.out.println(f); 13 14 FinalData f1 = new FinalData(); 15 System.out.println(f1); 16 } 17 public String toString() { 18 return 19 "valueOne = " + valueOne 20 + " " + "i4 = " + i4 21 + " " + "INT_5 = " + INT_5; 22 } 23 }
注意到:i4和INT_5的差别:类的不同对象中INT_5只在地一个对象创建的时候初始化一次,而i4则在每个对象创建的时候初始化一次。
关于名字屏蔽和C++的原则是不同的
C++中子类的重载函数会屏蔽掉基类中的其他函数:
1 #include <iostream> 2 3 class Homer { 4 public: 5 char doh(char c) { 6 std::cout << "doh(char)" << std::endl; 7 return ‘d‘; 8 } 9 10 float doh(float f) { 11 std::cout << "doh(float)" << std::endl; 12 return 1.0f; 13 } 14 }; 15 16 class Milhouse {}; 17 18 class Bart : Homer { 19 public: 20 void doh(Milhouse& m) { 21 std::cout << "doh(Milhouse)" << std::endl; 22 } 23 }; 24 25 int main() { 26 Bart b; 27 //b.doh(1); 28 b.doh(‘x‘); 29 //b.doh(1.0f); 30 Milhouse m; 31 b.doh(m); 32 return 0; 33 }
而java不会
1 class Homer { 2 char doh(char c) { 3 System.out.println("doh(char)"); 4 return ‘d‘; 5 } 6 7 float doh(float f) { 8 System.out.println("doh(float)"); 9 return 1.0f; 10 } 11 } 12 13 class Milhouse {} 14 15 class Bart extends Homer { 16 void doh(Milhouse m) { 17 System.out.println("doh(Milhouse)"); 18 } 19 20 @Override char doh(char c) { 21 System.out.println("Bart:doh(char)"); 22 return ‘c‘; 23 } 24 } 25 26 public class Hide { 27 public static void main(String[] args) { 28 Bart b = new Bart(); 29 b.doh(1); 30 b.doh(‘x‘); 31 b.doh(1.0f); 32 b.doh(new Milhouse()); 33 } 34 }
还有就是要注意初始化顺序
1 class Insect { 2 Insect() { 3 System.out.println("Insect::Insect()"); 4 } 5 6 static int i = printInit("static Insect::i"); 7 8 static int printInit(String s) { 9 System.out.println(s); 10 return 5; 11 } 12 13 int j = printInit("Insect::j"); 14 } 15 16 public class Beetle extends Insect { 17 Beetle() { 18 System.out.println("Beetle::Beetle()"); 19 } 20 21 public static void main(String[] args) { 22 System.out.println("Beetle::main()"); 23 new Beetle(); 24 } 25 26 int k = printInit("Beetle::k"); 27 static int l = printInit("static Beetle::l"); 28 }
时间: 2024-10-27 00:13:52