看起来您似乎无法理解对象和面向对象编程的基本概念。以举例说明;这个类代表一种东西,即汽车:
public class Car{
// Licence plate number. This is private, so it can
// not be accessed directly from outside the class.
private String hiddenRegNr = "";
private static String description = "This is a car".
// The constructor, which sets the value of hiddenRegNr
public Car(String regNr){
hiddenRegNr = regNr;
}
// Method for reading hiddenRegNr, the only
// way to access it after instantiation.
public String getRegNr(){
return hiddenRegNr;
}
// A static method. Can be used withouth instantiation.
public static String getDesc(){
return description;
}
}从其他一些类中,你可以调用这个类,然后创建它的实例;不同车型的实际表示。它们代表不同的汽车,但是基于相同的“模型”,即汽车类。
Car myFirstCar = new Car("SR12345");
Car myOtherCar = new Car("XZ54321");现在你有两辆不同的车,有两个不同的注册号码。这些是汽车类型的独立实例。它们存在于内存中,可能包含不同的值(在本例中为不同的注册号)。
myFirstCar.getRegNr(); // Will return SR12345
mySecondCar.getRegNr(); // will return xz54321首先要注意的是,每辆车只能指定一次注册号,即创建时。这是构造函数的要点:它设置值,并在创建对象(实例)时执行其他需要完成的操作。
现在,请注意getRegNr()和getDesc()之间的区别:关键字“Static”表示第二个方法直接与类相关,而不是与每个实例相关。这意味着:
调用getDesc()是在类上进行的,而不是实例:
Car.getDesc();
调用getDesc()将为类car的所有实例返回相同的值
对于Car的所有实例,变量描述(也是静态的)将是相同的
静态方法getDesc()无法访问变量hiddenRegNr,因为该变量与特定实例相关。尝试从静态上下文(例如getDesc())引用实例中的变量将导致抛出异常。您可能会说调用时不会设置hiddenRegNr
Car.getDesc();
因为构造函数从未被调用过,所以从未给出任何值。