How do I call methods of an instantiated object of an inner class in Java? I tried doing so and I am getting an error.
Posted by PutPsychological9682@reddit | learnprogramming | View on Reddit | 7 comments
I get the follwing error:
----------
ERROR!
Main.java:42: error:
x.setYear(2000);
ERROR!
\^
Main.java:42: error: illegal start of type
x.setYear(2000);
\^
2 errors
-------------------------
with the following code:
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);
}
Temporary_Pie2733@reddit
The year isn’t something you should be able to change; drop the setter entirely and pass the year to the constructor as an argument. Mileage isn’t something you should be able to change arbitrarily, either. Have the constructor take an optional non-zero mileage, and provide a method that can increment the mileage by some positive (or at least non-negative) amount.
nekokattt@reddit
this totally ignores the real problem
gamerman_007@reddit
x.setYear and is a method call. I think this should be in a block
helpprogram2@reddit
The start of your program is the main method. All your code starts inside of there.
long_time_in_entish@reddit
Think about what the class constructor is doing here.
dtsudo@reddit
Your code needs to be inside a method.
dmazzoni@reddit
Statements like Car x = new Car() and x.setYear(2000) need to live inside of a method. Try moving those two lines of code inside main, right after your System.out.println.