class AnIntegerNamedX {
static int x;
//
这里写成
static
,结果就变成全是
2
了,因为类变量是被实例所共
享的,包括
myX
和
anotherX
调用
anotherX
时所有的所有实例都改变了。
public int x() {
return x;
}
public void setX(int newX) {
x = newX;
}
}
public class Practice{
public static void main(String args[]){
AnIntegerNamedX myX = new AnIntegerNamedX();
AnIntegerNamedX anotherX = new AnIntegerNamedX();
myX.setX(1);
anotherX.x = 2;
//
这里把
X
的值改成
2
,所有实例的
X
都是
2
了,因为类变
量是被所有实例共享的,任何实
例都可以对类变量做最终的修改
System.out.println("myX.x = " + myX.x());
System.out.println("anotherX.x = " + anotherX.x());
}
}
类体的定义包括成员变量的定义和方法的定义。
1
、成员变量包括实例变量和类变量;而成员方法包括实例方法、类方法,当然还有一种特
殊的构造方法。
2
、类变量、类方法就是类中的变量、方法,必须是静态的,要加
static
;故其又称静态变
量、静态方法。
3
、成员变量、成员方法是对象或实例中的变量、方法,不加
static
;
类变量
:静态域,静态字段,或叫静态变量,它属于该类所有实例共有的属性,在内存中只
有一个地方存储这个变量。
而且所有的实例都可以修改这个类变量的值
(前提是这个类变量
没有被
final
修饰,否则是常量了),而且访问类变量的时候不用实例,直接用类就可以了。
类方法
:和类变量一样,可以不用实例,直接用类就可以调用类方法。
实例变量
:实例域,实例字段,或叫成员变量。
实例方法
:或叫成员方法,必须先有实例,然后才能通过实例调用该实例方法。
使用方法
:类方法可以直接调用类变量和类方法
类方法不可以直接调用实例变量和实例方法
类方法中没有
this
,因为没有实例,
this
不知道调用哪个实例
类方法可以从类里面直接访问类成员
实例方法可以调用类方法,访问类变量,但是不提倡这样做,会把类方法和类变
量混淆成实例方法和实例变量
程序实例:
class AnIntegerNamedX {
int x;
//
这个是成员变量
public int x() {
//
成员方法
return x;
}
public void setX(int newX) {
//
成员方法
x = newX;
}
}
public class Practice{
public static void main(String args[]){
AnIntegerNamedX myX = new AnIntegerNamedX();
AnIntegerNamedX anotherX = new AnIntegerNamedX();
myX.setX(1);
anotherX.x = 2;
System.out.println("myX.x = " + myX.x());
System.out.println("anotherX.x = " + anotherX.x());
}
}