import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class NestedClass {
private class Node {
private int x;
private int y;
public Node(int a, int b){
this.x = a;
this.y = b;
}
}
private static class StaticNode {
private int x;
private int y;
static String tag = "Nest class & static"; //every StaticNode has a string points to the tag string at the same address
//如果使它静态化(使用static关键字修饲),这个字段将只获得内存一次
static int number;
public StaticNode(int a, int b){
this.x = a;
this.y = b;
number++;
System.out.println("static node no." + number);
}
@Override
public String toString(){
System.out.println(number + ": [" + x +", " +y + "]");
return "";
}
private static int getNumber(){
System.out.println("only can get static variable: number " + number);
return number;
}
private static void changeNumber(int a) {
number = a;
}
}
class NestMap {
private List<Integer> x;
private List<Integer> y;
Node n; //private nested class can be instanciated by other classes under the same super class
public NestMap(List<Integer> a, List<Integer> b){
this.x = a;
this.y = b;
this.n = new Node(0,0);
}
}
static {
System.out.println("it's the nested block .....");
}
public static void main(String[] args) {
NestedClass nc = new NestedClass();
Node node = nc.new Node(1,2); //private inner class can be accessed by the outer class instance
NestMap nm = nc.new NestMap(new ArrayList<>(), new ArrayList<>());
nm.n = node;
//static class is a nested class, not inner class,cannot be instantiated with the outer class
StaticNode node2 = new StaticNode(1,2);
StaticNode node3 = new StaticNode(2,3);
node3.toString();
/*
* 如果在任何方法上应用static关键字,此方法称为静态方法。
* 静态方法属于类,而不属于类的对象。可以直接调用静态方法,而无需创建类的实例。
* 静态方法可以访问静态数据成员,并可以更改静态数据成员的值。
* */
int num = 100 + StaticNode.getNumber();
StaticNode.changeNumber(num);
StaticNode.getNumber();
StaticNode node4 = new StaticNode(3,4);
node4.toString();
}
}
it's the nested block .....
static node no.1
static node no.2
2: [2, 3]
only can get static variable: number 2
only can get static variable: number 102
static node no.103
103: [3, 4]
静态方法有两个主要限制。
*静态方法不能直接使用非静态数据成员或调用非静态方法。
* this和super两个关键字不能在静态上下文中使用。
为什么java main方法是静态的?
这是因为对象不需要调用静态方法,如果它是非静态方法,jvm首先要创建对象,然后调用main()方法,这将导致额外的内存分配的问题。
//原文出自【易百教程】:https://www.yiibai.com/java/static-keyword-in-java.html