我刚刚开始Java编程,我正在关注这个例子,我不断得到这个“无法从静态内容引用的非静态变量”错误。这段代码应该打印出节奏,速度和档位。我在Bicycle bike1=new Bicycle();
和Bicycle bike2=new Bicycle();
收到错误。这是代码:
public class BicycleDemo
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Bicycle bike1= new Bicycle();
Bicycle bike2= new Bicycle();
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStatments();
bike2.changeCadence(40);
bike2.speedUp(12);
bike2.applyBreaks(3);
bike2.printStatments();
}
class Bicycle
{
int cadence=0;
int speed=0;
int gear=1;
void changeCadence(int value)
{
cadence=value;
}
void changeGear(int value)
{
gear=value;
}
void speedUp(int increment)
{
speed=speed+increment;
}
void applyBreaks(int decrement)
{
speed=speed-decrement;
}
void printStatments()
{
System.out.println("Cadence:"+cadence+"Speed:"+speed+"Gear:"+gear);
}
}
答案 0 :(得分:1)
问题是Bicycle
类是一个内部类,不能在static
方法中直接实例化。只需将其移到BicycleDemo
类:
public class BicycleDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Bicycle bike1= new Bicycle();
Bicycle bike2= new Bicycle();
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStatments();
bike2.changeCadence(40);
bike2.speedUp(12);
bike2.applyBreaks(3);
bike2.printStatments();
}
}
//note the braces ( } ) up here
class Bicycle {
//definition here...
}
答案 1 :(得分:0)
将class Bicycle
更改为static class Bicycle
,或者最好将其移至单独的文件(Bicycle.java
)。
答案 2 :(得分:0)
如果没有引用外部类的对象,则无法访问非静态内部类。
在这种情况下,您无法实例化Bicycle bike1= new Bicycle();
您在静态上下文中工作(public static void main(String [] args)),因此您必须首先创建外部类(BicycleDemo)的实例,然后创建内部类的实例。 在这种情况下,您需要写:
BicycleDemo demo = new BicycleDemo ();
Bicycle bike1= demo.new Bicycle();
Bicycle bike2= demo.new Bicycle();
...