class Account {
public static int number1 = 1;// 静态变量(类变量)
// 它不属于任何一个对象,被多个对象共享
public int number2 = 2;
public Account() {
System.out.println("constructor");
}
/*
* static语句块 在类被加载的时候就会执行, 只会执行一次,用来对静态的变量赋值 优先于构造方法的执行
*/
static {
System.out.println("static");
number1 = 100;
}
// 静态方法中不能访问非静态变量
// 静态方法中不能使用this
public static void showNumber1() {
// showNumber2();
System.out.println(number1);
// System.out.println(number2);
// Cannot make a static reference to the non-static field number2
}
// 非静态方法可以访问静态的内容和非静态的属性和方法
public void showNumber2() {
System.out.println(number2);
System.out.println("非静态方法访问静态变量" + number1);
}
}
public class StaticDemo {
public static void main(String[] args) {
/*
* Account acc1 = new Account(); acc1.number1++; acc1.showNumber1();
* //acc1.showNumber2();
*
* Account acc2 = new Account(); acc2.showNumber1(); //
* acc2.showNumber2();
*/
/*Account.number1++;
System.out.println(Account.number1);
Account.showNumber1();*/
Account acc1 = new Account();
acc1.showNumber2();
Account acc2 = new Account();
acc2.showNumber2();
}
}
a.以类命名实例来说,首字母是大写。import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
public class ImportStatic {
public static void main(String[] args) {
Scanner scanner = new Scanner(in);
out.print("请输入姓名");
out.printf("%s 你好!%n", scanner.nextLine());
}
}
import static的名称冲突问题——有些名称冲突编译程序可通过以下顺序来解析