Java 中static关键字

static 修饰的变量是 同一个类创建的所有对象 共享的。

若确定了 同一个类创建的所有对象的某个属性一致的(比如,都是中国国籍,都是男生等),则该属性可以用static修饰。

在创建的所有对象的某个属性相同的前提下,用 static 修饰类的某个属性,是为了创建多个对象时节省内存空间。

程序运行时有专门的静态区,用来存储 静态属性静态方法

static关键字注意事项:

(1)在静态方法中没有 this 关键字

(2)静态方法只能访问静态的成员变量和静态的成员方法

静态是随着类的加载而存在的,而普通的变量和方法(包括 this)是随着对象的创建而存在的。

 

package level2;

class AA{
	public static void show() {
		System.out.println("AA");
	}
}
class BB extends AA{
	public static void show() {
		System.out.println("BB");
	}
}
public class staticDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		AA a = new BB();
		a.show();
		BB b = new BB();
		b.show();
		AA.show();
		BB.show();
	}

}

测试结果:

AA
BB
AA
BB
 

关于这段代码,个人不是很理解,欢迎大家解惑。

你可能感兴趣的:(Java)