Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active December 19, 2021 10:20
Show Gist options
  • Save sunmeat/eade02f5ebfba2b69b7e to your computer and use it in GitHub Desktop.
Save sunmeat/eade02f5ebfba2b69b7e to your computer and use it in GitHub Desktop.
static initializer block
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