错误代码
public class test1 {
public static void main(String[] arguments) {
int a=12;
int b=plus(a);
System.out.print(b);
}
int plus(int a){
int c=10;
return a+c;
}
}
报错
解决方法
1.在使用的方法前加上static
public class test1 {
public static void main(String[] arguments) {
int a=12;
int b=plus(a);
System.out.print(b);
}
static int plus(int a){//改正
int c=10;
return a+c;
}
}
2.实例化
public class test1 {
public static void main(String[] arguments) {
test1 t=new test1();
int a=12;
int b=t.plus(a);
System.out.print(b);
}
int plus(int a){
int c=10;
return a+c;
}
}
原因分析
对于一个类而言,如果要使用他的成员,那么普通情况下必须先实例化对象后(连接),通过对象的引用才能够访问这些成员。
如果不实例化对象而想访问类,使用static修饰方法。因为被static修饰的成员变量和成员方法独立于该类的任何对象。也就是说,它不依赖类特定的实例,被类的所有实例共享。
详细static作用见:Java中static作用及用法详解_fengyuzhengfan的专栏-CSDN博客_static在java中的用法
/*如有错误,欢迎指正*/