不能从静态上下文引用非静态方法 [英] Nonstatic method cannot be reference from a Static context

查看:29
本文介绍了不能从静态上下文引用非静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的班级是这样的:

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.

这篇关于不能从静态上下文引用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆