预测以下Java程序的输出:
null
例1:
JAVA
// filename: Test.java class Test { // Declaring and initializing integer variable int x = 10 ; // Main driver method public static void main(String[] args) { // Creating an object of class inside main() Test t = new Test(); // Printing the value inside the object by // above created object System.out.println(t.x); } } |
输出
10
输出说明:
在Java中,可以使用类的声明初始化成员。当初始化值可用且可以将初始化放在一行上时,此初始化工作正常(请参阅 这 更多细节)。
例2:
JAVA
// filename: Test.java // Main class class Test { // Declaring and initializing variables int y = 2 ; int x = y + 2 ; // main driver method public static void main(String[] args) { // Creating an object of class inside main() method Test m = new Test(); // Printing the value of x and y // using above object created System.out.println( "x = " + m.x + ", y = " + m.y); } } |
输出
x = 4, y = 2
输出说明:
一个非常简单的解决方案:首先用值2初始化y,然后将x初始化为y+2。所以x的值变成了4。
你有没有想过当一个成员在类声明和构造函数中被初始化时会发生什么?
例3:
JAVA
// filename: Test.java // Main clas public class Test { // Declaring and initializing integer with custom value int x = 2 ; // Constructor of this class // Parameterized constructor Test( int i) { x = i; } // Main driver method public static void main(String[] args) { // Creating object of class in main() Test t = new Test( 5 ); // Printing the value System.out.println( "x = " + t.x); } } |
输出
x = 5
输出说明:
使用Java中的类声明进行初始化就像使用 初始值设定项列表 在C++中。因此,在上面的程序中,构造函数中指定的值覆盖了之前的值x,即2,x变为5。
例4:
JAVA
// filename: Test2.java // Class 1 // Helper class class Test1 { // Constructor of this class Test1( int x) { // Print statement whenever this constructor is // called System.out.println( "Constructor called " + x); } } // Class 2 // Class contains an instance of Test1 // Main class class Test2 { // Creating instance(object) of class1 in this class Test1 t1 = new Test1( 10 ); // Constructor of this class Test2( int i) { t1 = new Test1(i); } // Main driver method public static void main(String[] args) { // Creating instance of this class inside main() Test2 t2 = new Test2( 5 ); } } |
输出
Constructor called 10Constructor called 5
输出说明:
第一个t2对象在main方法中实例化。由于局部变量的初始化顺序排在第一位,所以类Test2中的构造函数、实例变量(t1)首先被分配给内存。在这一行中,创建了一个新的Test1对象,在类Test1中调用构造函数,并打印“constructor called 10”。接下来,调用Test2的构造函数,再次创建Test1类的新对象,并打印“constructor called 5”。
如果您发现任何答案/解释不正确,或想分享有关上述主题的更多信息,请发表评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END