public class Truck {
int weight;
public class BridgeOfficer {
private int maxWeight;
public BridgeOfficer(int normalWeight) {
this.maxWeight = normalWeight;
}
public boolean checkTruck(Truck truck) {
if (truck.weight > maxWeight) {
return false;
} else {
return true;
}
}
}
public static void main(String[] args) {
Truck first = new Truck();
first.weight = 10000;
Truck second = new Truck();
second.weight = 20000;
BridgeOfficer officer = new BridgeOfficer(1500);
System.out.println("Truck 1! Can I go, officer?");
boolean canFirstTruckGo = officer.checkTruck(first);
System.out.println(canFirstTruckGo);
System.out.println();
System.out.println("Truck 2! And can I?");
boolean canSecondTruckGo = officer.checkTruck(second);
System.out.println(canSecondTruckGo);
}
}
I'm new with Java, and when run this code give me this error: non-static variable this cannot be referenced from a static context BridgeOfficer officer = new BridgeOfficer(1500);...I search a lot in google but I can't fix it
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Thomas
29 May 2021, 09:26useful
There are several ways to fix this and to understand the problem you need to read about inner classes (however I think the topic may be to advanced for now). The easiest way is to a) avoid inner classes for now or b) to make them static.
b) add the static keyword to the BridgeOfficers class declaration like public static class BridgeOfficer {
a) move the BridgeOfficers class declaration outside the Truck class and remove the public keyword
[ c) not recommended till you learned about that topic: keep the inner class and when instanciating the object take care of the outer object like: BridgeOfficer officer = new Truck().new BridgeOfficer(1500); ]
+1
Hisham Thabet
29 May 2021, 11:35
Thank You a lot , Thomas .Really now I understand and fix it
Good luck
0