I'm trying to call methods on an instance of an inner class in Java, but I'm running into errors. The specific error messages I get are:
ERROR!
Main.java:42: error: expected
x.setYear(2000);
ERROR!
Main.java:42: error: illegal start of type
x.setYear(2000);
Here's the code I'm using:
class Main {
public static void main(String[] args) {
System.out.println("Try programiz.pro");
}
public class Car {
private int mileage = 0;
private int year = 0;
public Car() {}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return this.mileage;
}
public int getYear() {
return this.year;
}
}
Car x = new Car();
x.setYear(2000);
}
5 Answers
It looks like you need to move your declarations and method calls for `Car x = new Car();` and `x.setYear(2000);` inside the `main` method. They can't be at the class level in this context because you can only execute statements inside methods.
You might want to rethink how you're setting `year`. It could be better to pass the year as an argument to the constructor of the `Car` class, instead of having a setter. That way you avoid arbitrarily changing it after instantiation. Same goes for `mileage`!
Absolutely right! You're trying to access an instance of the inner class outside any method, which won't work. Also, if you're going to use an inner class like this, consider making it static if you plan to create instances in a static context.
Right, calling `x.setYear` is an instance method call, so make sure you place that inside a method body. Also, check how you structure your classes if you want them to interact properly!
Remember, the main method is where all the action happens in Java. Any instance creation or method calling should go inside this method. Just move those lines after your `System.out.println`. You’ll be set!
Got it! I'll adjust it right now, thanks!