How do I call methods of an inner class object in Java?

0
9
Asked By CoolDude123 On

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

Answered By JavaFan99 On

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.

Answered By CleverCoder On

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`!

Answered By CodeWhiz44 On

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.

Answered By DevRocket On

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!

CoolDude123 -

Got it! I'll adjust it right now, thanks!

Answered By TechGuru88 On

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!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.