不能从静态上下文引用非静态方法

2022-01-19 00:00:00 switch-statement java

我的班级是这样的:

public class Month
 {
private int numOfMonth;
private int monthNum;

public int monthNum()
{
    return monthNum = 1;
}

public void setMonthNum(int monthNum){

    switch (monthNum)
    {
    case 1: System.out.println("January"); break;
    case 2: System.out.println("February");break;
    case 3: System.out.println("March");break;
    case 4: System.out.println("April");break;
    case 5: System.out.println("May");break;
    case 6: System.out.println("June");break;
    case 7: System.out.println("July");break;
    case 8: System.out.println("August");break;
    case 9: System.out.println("September");break;
    case 10: System.out.println("October");break;
    case 11: System.out.println("November");break;
    case 12: System.out.println("December");break;
    }

}

    public String getName() 
    {
        return "" + monthNum;
    }

}

我的驱动如下:

import java.util.Scanner;

public class monthDriver
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);

    System.out.println("Enter month number: ");
    int monthNum = in.nextInt();

    System.out.println("Month number " + monthNum + " is the month of " + Month.getName());

}
 }

我得到编译时错误:

"monthDriver.java:12: error: non-static method getName() cannot be referenced from a static context
    System.out.println("Month number " + monthNum + " is the month of " + Month.getName());1 error"

请记住,我是一名学生,学术诚信对我很重要,为什么我会收到这样的错误?另外,以后有什么建议可以提高我的编码效率吗?感谢您所有的时间和精力.非常感谢.

Keeping in mind that I am a student, and academic integrity is important to me, Why am I receiving such an error? Also, are there any suggestion that could be made improve my coding efficiency in the future? Thank you for all your time and effort. It is GREATLY appreciated.

推荐答案

对于初学者来说,如果你想在不先实例化类本身的情况下访问类的方法(在你的情况下为 Month),但直接使用 Month.getName(),那么该方法必须定义为静态的.

Well for starters, if you want to access a method of a class (in your case Month) without first instantiating the class itself, but directly with Month.getName(), then that method must be defined as static.

关于什么时候在一个类中使用静态或非静态方法,你可以在网上找到这么多的文章来填满一个库:-)

About when to use static or non-static methods in a class, you can find so much articles online to fill up a library :-)

关于上面代码的另一个小注释.您可能对使用枚举感兴趣,而不是使用开关.

Another small note about the code above. Instead of using a switch you might be interested in using an enumeration.

相关文章