实例变量
- 实例变量声明在一个类中,但在方法、构造方法和语句块之外;
- 当一个对象被实例化之后,每个实例变量的值就跟着确定;
- 实例变量在对象创建的时候创建,在对象被销毁的时候销毁;
- 实例变量的值应该至少被一个方法、构造方法或者语句块引用,使得外部能够通过这些方式获取实例变量信息;
- 实例变量对于类中的方法、构造方法或者语句块是可见的。一般情况下应该把实例变量设为私有。通过使用访问修饰符可以使实例变量对子类可见;
- 实例变量具有默认值。数值型变量的默认值是0,布尔型变量的默认值是false,引用类型变量的默认值是null。变量的值可以在声明时指定,也可以在构造方法中指定;
- 实例变量可以直接通过变量名访问。但在静态方法以及其他类中,就应该使用完全限定名:ObejectReference.VariableName。
类变量(静态变量)
- 类变量也称为静态变量,在类中以static关键字声明,但必须在方法构造方法和语句块之外。
- 无论一个类创建了多少个对象,类只拥有类变量的一份拷贝。
- 静态变量除了被声明为常量外很少使用。常量是指声明为public/private,final和static类型的变量。常量初始化后不可改变。
- 静态变量储存在静态存储区。经常被声明为常量,很少单独使用static声明变量。
- 静态变量在程序开始时创建,在程序结束时销毁。
- 与实例变量具有相似的可见性。但为了对类的使用者可见,大多数静态变量声明为public类型。
- 默认值和实例变量相似。数值型变量默认值是0,布尔型默认值是false,引用类型默认值是null。变量的值可以在声明的时候指定,也可以在构造方法中指定。此外,静态变量还可以在静态语句块中初始化。
- 静态变量可以通过:ClassName.VariableName的方式访问。
- 类变量被声明为public static final类型时,类变量名称必须使用大写字母。如果静态变量不是public和final类型,其命名方式与实例变量以及局部变量的命名方式一致。
class TiXing{
float up,height;
static float down; TiXing(float x,float y,float z){
up=x;
height=y;
down=z;
}
} public class ep3_9{
public static void main(String args[]){
TiXing one=new TiXing(1,2,3);
System.out.println("one's down is:"+one.down);
TiXing two=new TiXing(4,5,6);
System.out.println("one's down is:"+one.down);
System.out.println("two's down is:"+two.down); System.out.println("TiXing's down is:"+TiXing.down);
}
}
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAARYAAABWCAIAAACFAC7AAA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5RWyqNXV+TBlfCmNkAILAQQAgsBhMBCACGwEECIe1mI36ZgOu5loYXHIzAbioXWFtuBzScwyvOWrAnk7hZKnEi9qZjDD0G30E9MvbEYHr1b4r0c0QEnN1b6pcSYzRsPVtKX3N3xVN1I6g9ewcqlDaJgoWV6qc17Zm+GyOGgMfymtnJD0v1nUhGmfKoXOiK+Hix01jEDRV36myPeusouhIjMQsq41CV65L5ru1WUzN1DpHipU6VISb+ruqJHyeCqi4UO5HILNXeDFvLG6xaqN7rxrur2A6V4LHQl6RaS2ssyUjhHsqIkxn7ImIW25OkWWpL0Z8WDgzktFDzHwy3VtVARk2ihSAAWupJcC+mnamwWOvqqvC+h61EGjXWlsO7fTT9kr617svBPMvb/a3V/1PqbZuR+dyC+KKd/i2Z+4yFL5SLpK9cbytdx6dT1S2mlPHp1RR6MMOc7cl4LAVzGnBZanDdyAJcxrYUA7gEWAgiBhQBCYCGAEFgIIAQWAgiBhQBCYCGAEFgIIAQWAgiBhQBCYCGAEFgIIAQWAojwH2IY7gbFY6LqAAAAAElFTkSuQmCC" alt="" />
实例方法和类方法对实例变量和类变量的访问
实例方法可以对当前对象的实例变量进行操作,也可以对类变量进行操作。实例方法由实例对象调用。
类方法不能访问实例变量,只能访问类变量。类方法由类名或者实例对象调用。类方法中不能出现this或者super关键字
class TiXing{
private float up,height;
private static float down; TiXing(float x,float y,float z){
up=x;
height=y;
down=z;
}
public void display(){
System.out.println("up is:"+up+"height is:"+height+"down is:"+down);
}
public static void change(float number){
down=number;
//System.out.println("height:"+height);//出错
}
} public class ep3_9{
public static void main(String args[]){
TiXing one=new TiXing(1,2,3);
one.display();
TiXing two=new TiXing(4,5,6);
one.display();
two.display(); //TiXing.display();//出错
one.change(101);
one.display();
two.change(102);
two.display();
}
}
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWYAAABwCAIAAACivE1zAAAKo0lEQVR4nO2cMbrbOAyEdec9zd6Gl0iZKk3a3GCLffGnJwLDAUhJpDR/Zcog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