Last active
December 19, 2021 10:20
-
-
Save sunmeat/eade02f5ebfba2b69b7e to your computer and use it in GitHub Desktop.
static initializer block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.alex.static; | |
class StaticFields { | |
// статический блок инициализации | |
// обычно располагается после объявления статических полей | |
// перед static не пишется public или private | |
// позволяет выполнять вычисления для инициализации | |
static { | |
System.out.println("статический блок инициализации 1"); | |
b = 15; | |
// b = a * 5; // cannot reference a field before it is defined! | |
// c = 20; // cannot make a static reference to the non-static field! | |
} | |
static int a = 3; | |
static int b; // по умолчанию 0 | |
int c; | |
// статических блоков инициализации может быть несколько | |
static { | |
System.out.println("статический блок инициализации 2"); | |
a = b * 2; | |
} | |
public void commonMeth() { | |
System.out.println("обычный метод:"); | |
System.out.println("a = " + a); | |
System.out.println("b = " + b); | |
System.out.println("c = " + c); | |
} | |
// статический метод | |
public static void staticMeth() { | |
System.out.println("статический метод:"); | |
System.out.println("a = " + a); | |
System.out.println("b = " + b); | |
// System.out.println("c = " + c); // к обычным полям не достучаться, this и super - недоступны | |
} | |
} | |
class Program { | |
public static void main(String[] args) { | |
System.out.println("hello from main!"); | |
System.out.println(StaticFields.a); | |
System.out.println(StaticFields.b); | |
// System.out.println(StaticFields.c); | |
// cannot make a static reference to the non-static field | |
StaticFields.staticMeth(); | |
//StaticFields.commonMeth(); | |
// cannot make a static reference to the non-static method | |
StaticFields sf = new StaticFields(); | |
System.out.println(sf.a); | |
System.out.println(sf.b); | |
System.out.println(sf.c); | |
sf.staticMeth(); // not recommended! | |
sf.commonMeth(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment