Ada*_*tan 69 java static-initialization
static块内初始化有什么区别:
public class staticTest {
static String s;
static int n;
static double d;
static {
s = "I'm static";
n = 500;
d = 4000.0001;
}
...
Run Code Online (Sandbox Code Playgroud)
和个人静态初始化:
public class staticTest {
static String s = "I'm static";
static int n = 500;
static double d = 4000.0001;
....
Run Code Online (Sandbox Code Playgroud)
Ric*_*lly 83
静态初始化块允许更复杂的初始化,例如使用条件:
static double a;
static {
if (SomeCondition) {
a = 0;
} else {
a = 1;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,当不仅仅需要构造时:使用构建器来创建实例时,除了创建静态字段之外,还需要进行异常处理或工作.
静态初始化块也在内联静态初始化程序之后运行,因此以下内容有效:
static double a;
static double b = 1;
static {
a = b * 4; // Evaluates to 4
}
Run Code Online (Sandbox Code Playgroud)
gaw*_*awi 16
典型用法:
private final static Set<String> SET = new HashSet<String>();
static {
SET.add("value1");
SET.add("value2");
SET.add("value3");
}
Run Code Online (Sandbox Code Playgroud)
没有静态初始化程序,你会怎么做?
Pau*_*ora 10
初始化期间的异常处理是另一个原因.例如:
static URL url;
static {
try {
url = new URL("https://blahblah.com");
}
catch (MalformedURLException mue) {
//log exception or handle otherwise
}
}
Run Code Online (Sandbox Code Playgroud)
这对于烦人地抛出已检查异常的构造函数(如上所述)或者可能容易出现异常的更复杂的初始化逻辑非常有用.
我们使用构造函数有条件地初始化实例变量。
如果你想有条件地初始化类/静态变量,并且想在不创建对象的情况下完成它(构造函数只能在创建对象时调用),那么你需要静态块。
static Scanner input = new Scanner(System.in);
static int widht;
static int height;
static
{
widht = input.nextInt();
input.nextLine();
height = input.nextInt();
input.close();
if ((widht < 0) || (height < 0))
{
System.out.println("java.lang.Exception: Width and height must be positive");
}
else
{
System.out.println("widht * height = " + widht * height);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以在内部使用try / catch块,static{}如下所示:
MyCode{
static Scanner input = new Scanner(System.in);
static boolean flag = true;
static int B = input.nextInt();
static int H = input.nextInt();
static{
try{
if(B <= 0 || H <= 0){
flag = false;
throw new Exception("Breadth and height must be positive");
}
}catch(Exception e){
System.out.println(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
PS:从这里引用!
| 归档时间: |
|
| 查看次数: |
68350 次 |
| 最近记录: |