Solution for :Cannot make a static reference to the non-static method

本文将详细解析Java编程中常见的静态引用非静态方法错误,通过实例分析并提供解决方案,帮助Java新手理解并避免此类低级错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    最近在学习java,作为java的菜鸟和以前C语言思维带来的影响,在弄java时经常犯一些比较低级的错误,弄清楚这些低级的错误对于理解java有很好的帮助。所以记录一下。
Cannot make a static reference to the non-static method 这个错误估计是最常见的,当时还觉得奇怪为什么是这样的情况呢。
比如我写了下面 一段java的测试小程序来检验一个字符串是否是数字:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestStrIsNum {
	   public  boolean isNumeric(String str){ 
		   Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+"); 
		   Matcher isNum = pattern.matcher(str);
		   if( !isNum.matches() ){
		       return false; 
		   } 
		   return true; 
		}

	   public static void main(String[] argv)
		{
                    String a =new String("-1000");
		    
                    //if (isNumeric(a)) error:Cannot make a static reference to the non-static method
                    TestStrIsNum test = new TestStrIsNum();    
                    if (test.isNumeric(a))  
                        System.out.println("a = -1000 is a number");	    
		} 
}
Analysis and soultion:
You can't make a static reference to the non-static method, so you can change the un-static method to a static method or you need to create an object using new operator and call the method by object.method().

stackoverflow上explaination:
http://stackoverflow.com/questions/23860661/cannot-make-a-static-reference-to-the-non-static-method
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值