Nonstatic method cannot be reference from a Static context(不能从静态上下文引用非静态方法)
问题描述
我的班级是这样的:
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.
这篇关于不能从静态上下文引用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不能从静态上下文引用非静态方法


- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01