java里类变量和实例变量的区别

如题所述

每次创建一个类的对象的时候,系统为它创建了类的每一个实例变量的副本。我们就可以从对象中访问该实例变量。
类变量或说静态变量跟实例变量是不一样的,不管为一个类创建了多少个对象,系统只为每个类变量分配一次存储空间。系统为类变量分配的内存是在执行main方法时马克-to-win, 就是在程序最最开始的时候(见下面StaticDemo的例子)。所有的对象共享了类变量。可以通过对象或者通过类本身来访问类变量。

Static fields
A field define as static, means there is only one such field shared by all objects
Instance fields
A field define without static, means each object has its own copy of fields


顺便提一句:通常用下面的形式,定义类的常量。(类或实例都可以访问)

static final double PI=3.14159;

静态方法(方法前冠以static)和实例方法(前面未冠以static)的区别

调用静态方法或说类方法时,可以使用类名做前缀,也可以使用某一个具体的对象名;通常使用类名。
非static的方法是属于某个对象的方法,而static的方法是属于整个类的,不被任何一个对象单独拥有;
由于static方法是属于整个类的,所以它不能操纵和处理属于某个对象的成员变量,而只能处理属于整个类的成员变量,也即,static方法只能处理static域或静态方法。实例方法可以访问实例域, 静态域或静态方法, 记住都行。
声明为static的方法有以下几条限制: 1.它们仅能调用其他的static方法。
2.它们只能访问static数据。
3.它们不能以任何方式引用this或super(关键 字super与继承有关,在下一章中描述)。

static method Have No this Reference
All instance methods have a hidden parameter—this
So,
Static
 method can’t access instance methods and fields; it can only invoke 
other static class members.It can access class members only. 
instance can use static method.
Instance methods:
If a method is declared without the static modifier keyword, 
that method is known as an instance method. Instance methods 
are associated with objects – not classes.
It can access either instance or class members. 
class StaticExa {
static int a = 4;
static int b = 9;
static void call() {
System.out.println("a = " + a);//静态方法可以访问静态属性
}
}
public class Test {
static int c = 43;
public static void main(String args[]) {
/*刚运行到这一步时,debug观察,StaticExa.a的值就等于42,Test.c的值就等于43,
说明系统在我们的程序一开始时,就会给所有的类变量赋值。如果是对象参考, 就是null,
见photoshop的例子*/ 
System.out.println("开始观察StaticExa.a和Test.c");


详情网上找“马克-to-win”,参考他的网站或他的百度空间:java第2章的内容

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-11-08
类变量也就是静态变量属于类。实例变量属于实例。
public class A {
//类变量(static)

public static int classVariable;
//实例变量

public int instanceVariable;

public static void main(String[] args) {
//类变量可以直接通过类使用。

A.classVariable = 2;
//实例变量只能先创建实例,只有存在实例,才会存在实例变量,然后通过示例引用。

A a = new A();
a.instanceVariable = 3;
//通过实例去引用类变量是可以的。反之不行。

System.out.println(a.classVariable);

}

}本回答被网友采纳
相似回答