0%

JavaSE Main Method

Code 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class WaterBottle {
private String brand;
private boolean empty;
public static void main(String[] args){
WaterBottle1 wb = new WaterBottle1();
System.out.print("Empty = " + wb.empty);
System.out.print(" ");
System.out.print("Brand = " + wb.brand);
}
}

class WaterBottle1 {
private String brand;
private boolean empty;
}

Code 2

1
2
3
4
5
6
7
8
9
10
public class WaterBottle {
private String brand;
private boolean empty;
public static void main(String[] args){
WaterBottle wb = new WaterBottle();
System.out.print("Empty = " + wb.empty);
System.out.print(" ");
System.out.print("Brand = " + wb.brand);
}
}

Code 3

1
2
3
4
5
6
7
8
9
10
public class WaterBottle {
private String brand;
private boolean empty;
public static void main(String... $n){
WaterBottle wb = new WaterBottle();
System.out.print("Empty = " + wb.empty);
System.out.print(" ");
System.out.print("Brand = " + wb.brand);
}
}

Code1 will have compiling error because WaterBottle1‘s attributes brand and empty are private;

Code2 will output “Empty = false Brand = null”.

Code3 varargs(可变长参数) are allowed in place of an array

Conclusion

The main method is an entry of a program, but it is still a class method, so it has right to access all attributes of that class.
By the way, Boolean fields initialize to false and references initialize to null, so empty is false and brand is null. Brand = null is output.

Reference