Java: When is a static initialization block useful?

前端 未结 13 1618
时光说笑
时光说笑 2020-11-30 16:49

What\'s the difference between initialization within a static block:

public class staticTest {

    sta         


        
13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 17:13

    We use constructors to initialize our instance variables(non-static variables, variables that belong to objects, not the class).

    If you want to initialize class variables(static variables) and want to do it without creating an object(constructors can only be called when creating an object), then you need static blocks.

    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);
        }
    }
    

提交回复
热议问题