So I was doing this exercise that simulates car instruments. There are three classes in total : FuelGauge
, Odometer
and CarInstrumentSimulator
(the one with the main method). The two first ones each have a constructor that I have defined. However whenever I type this in the main
:
public static void main(String[] args) {
CarInstrumentSimulator carInstrumentSimulator = new CarInstrumentSimulator();
FuelGauge fuel = carInstrumentSimulator.new FuelGauge();
Odometer odometer = carInstrumentSimulator.new Odometer(0, fuel);
I always get a CarInstrumentSimulator.FuelGauge cannot be resolved into a type error in eclipse(and same for the Odometer), however I got this line of code from the correction detailed in the website I got the exercise from ( https://www.leveluplunch.com/java/exercises/car-instrument-simulator/ ) I am very new to java and coding in general, so I was wondering : 1) what does this syntax mean:
FuelGauge fuel = carInstrumentSimulator.new FuelGauge();
2) why is there a problem with this syntax?
Thanks in advance ^^
I think that's a typo in the source . Try this instead:
FuelGauge fuel = new FuelGauge();
Odometer odometer = new Odometer(0, fuel);
There is no sensible answer to this question ...
what does this syntax mean :
FuelGauge fuel = carInstrumentSimulator.new FuelGauge();
... because the line in question is gibberish ;)
Valid method invocation on a Java object (such as carInstrumentSimulator
) would require dot notation, the method name and opening and closing brackets eg carInstrumentSimulator.doSomething()
but the above code does not have the opening and closing brackets, uses the word new
which is not a valid Java method name (since it is a reserved keyword) and new
is followed by FuelGauge()
which makes the whole thing uninterpretable.
More details on Java method construction here .
If FuelGauge
was declared inside CarInstrumentSimulator
then this syntax would be valid:
new CarInstrumentSimulator.FuelGauge();
Similarly, if CarInstrumentSimulator
exposed a creator method for FuelGauge
then this syntax would be valid:
carInstrumentSimulator.newFuelGauge();
But this syntax isn't valid in any circumstances: carInstrumentSimulator.new FuelGauge();
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.