After accessing static methods in static inner classes from main class in java, eclipse is giving warning

acidic_base :

I have a class -->

    public class Machine

There I have declared a static inner class -->

   public static class Parts

Inside static inner class I have declared two static methods -->

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

Now I want to access the methods from my main class App. I am using Eclipse IDE. I did -

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

Eclipse is letting me to do it. But it is giving me warning -
The static method engine from the type Machine.Parts should be accessed in a static way
The static method engine from the type Machine.Parts should be accessed in a static way

How to resolve this problem?

I have tried google search and stack overflow previous questions. But nowhere I could find the solution.

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

Machine engine is running
Machine battery is charging

Expected --> No warning

Actual --> Getting warning

GhostCat salutes Monica C. :

Here:

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

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

 machine.engine();

... invoking a static method, as if it were a non-static method of that class.

Yes, the above code works, but it is bad practice. If you meant to have "real" non-static methods, simply drop that keyword from the method signatures. Otherwise, change your code to:

Machine.Parts.engine();

Because that is what really happens in your code example.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322807&siteId=1