Java – Eclipse issues a warning after accessing a static method in a static inner class from the main class in Java

Eclipse issues a warning after accessing a static method in a static inner class from the main class in Java… here is a solution to the problem.

Eclipse issues a warning after accessing a static method in a static inner class from the main class in Java

I have a class – >

    public class Machine

I’ve declared a static inner class –>

   public static class Parts

In the static inner class, I declare two static methods –>

    public static void engine()
    public static void battery()

Now I want to access the methods in my main class app. I’m using the Eclipse IDE. I did it-

    Machine.Parts machine = new Machine.Parts();
    machine.engine();
    machine.battery();

Eclipse asked me to do it. But it gave me a warning –
Static method engines of type Machine.Parts should be accessed
statically
Static method engines of type Machine.Parts should be accessed
statically

How to solve this problem?

I’ve tried google search and stack overflow previous issues. But I was nowhere to be found.

My code-

Machine .java –>

package demo28;

public class Machine {

public static class Parts {
        public static void engine() {
            System.out.println("Machine engine is running");
        }
        public static void battery() {
            System.out.println("Machine battery is charging");
        }
    }
}

App.java –>

package demo28;

public class App {

public static void main(String[] args) {
        run(new Machine.Parts());
    }

public static void run(Machine.Parts machine) {
        machine.engine();
        machine.battery();
        System.out.println();
    }

}

Output — >

The machine engine is running
The machine battery is charging

Expect –> No warning

Actual –> received a warning

Solution

Here:

 Machine.Parts machine = new Machine.Parts();

You are creating an instance of the inner class. Then there you go:

 machine.engine();

… Call a static method as if it were a non-static method of the class.

Yes, the above code works, but this is bad practice. If you intend to have a “real” non-static method, simply remove the keyword from the method signature. Otherwise, change your code to:

Machine.Parts.engine();

Because that’s what really happens in your code example.

Related Problems and Solutions