请教一段Java代码

来源:百度知道 编辑:UC知道 时间:2024/05/19 11:29:14
class CarTest {
public static void main(String args[]) {
Car c = new Car();
c.licensePlate = "苏E12345";
c.speed = 80.0;
c.maxSpeed = 160.5;
System.out.println(c.licensePlate + " is moving at " + c.speed + " kilometers per hour.");
}
public static class Car
{
String licensePlate;
double speed;
double maxSpeed;
}
}
这是一段正确的代码,但我的疑惑是,在Car的那个Class中,我如果这样写
public class Car
{
static String licensePlate;
static double speed;
static double maxSpeed;
}
也就是在类的里面声明静态变量,而在声明类时则把static去掉,这样为什么就不行了呢?难道是在non-static类里就不能有static变量?请解释一下
那如果把class那段代码改成如下:
public static class Car
{
static String licensePlate;
static double speed;
static double maxSpeed;
}
那为什么又可以了呢?

static String licensePlate;
这样声明之后 就是静态常量,但是你
Car c = new Car();
c.licensePlate = "苏E12345";
这个地方对它进行了赋值 就相当于你尝试去修改常量。当然编译通过不了。

不能在成员类中定义static字段、方法和类(static final形式的常量定义除外)。因为一个成员类实例必然与一个外部类实例关联,这个static定义完全可以移到其外部类中去

http://guanjh.javaeye.com/blog/119938

当你在类中申明是变不加修饰符,默认修饰符是private,在其他类中私有变量在没有封装(getter/setter方法)时不能访问的。而静态类中的静态变量在静态方法中当然可以访问。