public class temp
{
public static void main(String[] args)
{
int a = 3;
int m;
m = trip(a);
System.out.println(m);
}
public static int trip(int b)
{
b *= 3;
return b;
}
}一个很简单的程序。。为什么public static int 一定要把static加进去呢? 不加进去就会报错
{
public static void main(String[] args)
{
int a = 3;
int m;
m = trip(a);
System.out.println(m);
}
public static int trip(int b)
{
b *= 3;
return b;
}
}一个很简单的程序。。为什么public static int 一定要把static加进去呢? 不加进去就会报错
Causes
If a Java program attempts to call a method that is not static, from a method that is static, the compiler or IDE (Integrated Development Environment) will generate an error. Programmers in the early stages of learning Java development are most likely to encounter this error, because they may not yet be familiar with the concepts involved in Object Oriented development through the Java language. A common situation in which the error tends to arise is when a program's main method is attempting to call another method defined in the same class, but which has not been declared as a static method.Solutions
The solution to problems calling non-static methods from static methods really needs to be approached in a way that suits the application. Making the method static by adding the "static" keyword to the method outline may stop the compiler from complaining and allow a program to run. However, the occurrence of the error may indicate that the method could be better handled by including it in a class declaration, calling it by first creating an object of the class.Read more: Java Cannot Make a Static Reference to a Non-Static Method | eHow.com http://www.ehow.com/info_8698319_java-static-reference-nonstatic-method.html#ixzz2ITzEQ1a3
1、该关键字主要用来修饰成员属性和方法。
2、静态不能直接调用非静态成员属性、方法。非静态可以调用静态成员属性、方法,也可以调用非静态属性、方法。
3、被static修饰的属性和方法是属于类的,可以称作类变量或类方法。可以通过实例名(对象名)访问,也可以通过类名直接访问(核心特点)。
4、静态方法中不能使用this.super关键字。
5、被static修饰的变量随着类的加载而加载,存在于方法区中,优先于对象存在,同时随着类的消失而消失,生命周期较对象变量(实例变量)更长,最占用内存。
很基础的小知识点。
不然就需要:Test t = new Test();//创建一个当前类对象,
t.show();//调用那个方法
这样也可以、。
普通方法和变量是当我们new一个实例的时候,在堆内存中进行初始化的。所以当我们试图用静态方法调用普通变量时,系统并没有为该变量分配内存,所以会静态方法不能调用普通变量和方法,只能new一个实例,为他开辟内存空间之后才可以调用。