-->

Main method is not static in class error [duplicat

2020-05-08 06:42发布

问题:

class useTent
{
    Scanner keyboard=new Scanner (System.in);

    public void main (String[] args)
    {

        Tent t= new Tent();
        HireContract hc = new HireContract();
        ProcessHire(t, hc);
    }
}

this is my code, and i keep getting the same error:

" Main method is not static in class useTent, please define the main method as: public static void main(String[] args) "

and when i make the it static i get the following error:

"C:\Users\Emma\Documents\opps ass1\useTent.java:22: error: non-static method ProcessHire(Tent,HireContract) cannot be referenced from a static context ProcessHire(t, hc);"

and also still the

"Error: Main method is not static in class useTent, please define the main method as: public static void main(String[] args)"

回答1:

The signature of main requires static just like the error is telling you

public static void main (String[] args) {

And you didn't post ProcessHire but I think you wanted a new and perhaps to save the reference

ProcessHire ph = new ProcessHire(t, hc);


回答2:

Java by default looks for a method

public static void main (String[] args) { }

or say

public static void main (String ...args) {}

args could be any name like public static void main (String ...arguments) {}

If you already have a public static void main method then you can have another main method which would act as normal method.

Now when you make the method static you get the other error because in a static context, calling a non static method(local to class) without initializing it's object would give error as java don't allow non static calls from static context/methods.

 non-static method error

One example solution is make ProcessHire method static:-

class UseTent
{
    Scanner keyboard=new Scanner (System.in);

public void main (String[] args)
    {

    Tent t= new Tent();
    HireContract hc = new HireContract();
    ProcessHire(t, hc);

    }

public static void processProcessHire(Tent tent,HireContract hireContract){
//your method definition
}
}

or if you can't make the method static then use approach below:-

class UseTent
{
    Scanner keyboard=new Scanner (System.in);

public void main (String[] args)
    {

    Tent t= new Tent();
    HireContract hc = new HireContract();
   new UseTent().ProcessHire(t, hc);

    }

public void processProcessHire(Tent tent,HireContract hireContract){
//your method definition
}
}


回答3:

The main class should be public static void main (String[] args)



回答4:

If ProcessHire method is static and in ABC class Try this,

class useTent{

    Scanner keyboard=new Scanner (System.in);

    public static void main (String[] args){

        Tent t= new Tent();
        HireContract hc = new HireContract();
        ABC.ProcessHire(t, hc);
   }
}

also follow Java Naming conventions.