Java變量的初始化方法有以下幾種:
int num = 10;
String name = "John";
public class MyClass {
private int num;
private String name;
public MyClass() {
this.num = 10;
this.name = "John";
}
}
public class MyClass {
private int num;
private String name;
{
this.num = 10;
this.name = "John";
}
}
public class MyClass {
private static int num;
private static String name;
static {
num = 10;
name = "John";
}
}
public class MyClass {
private int num;
private String name;
public void init() {
this.num = 10;
this.name = "John";
}
}
這些是常見的Java變量初始化方法,根據具體的需求和場景選擇合適的初始化方式。