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

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

问题描述

我的班级看起来像这样:

My Class is looking like this:

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

}

我的驱动程序如下:

My driver is as follows:

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天全站免登陆