调用某个类的方法,什么情况下需要实例化类,什么情况下不需要实例化呢?

来源:百度知道 编辑:UC知道 时间:2024/06/04 13:54:22
public class test
{
public static void main(String agrs[])
{
method1();
test t = new test();
t.method2();
}

public static void method1()
{
System.out.println("不需要实例化");
}

public void method2()
{
System.out.println("必须实例化");
}
}
什么情况下用静态方法啊,静态方法有什么用处啊?谢谢!

静态的成员变量和方法,都是不需要进行实例化类的。可以直接调用。
非静态的成员变量和方法,都要进行实例化类的。才可以调用。

public static void main(String agrs[])
{
method1();//标准写法应该是类名.方法 即 test.method1()
test t = new test();
t.method2();
}
你这个main方法正好在test类中.如果不在test类中method1()是不被认识的
static 是类方法不需要实例化 通过类名点出来就可以了

其实这个看你的需要,如果你认为你设计的某个方法,是每个对象都要用到的,并且每个对象使用方法一样的话就可以将你的方法声明为static的,比如Math里的方法,因为数学公式是固定的,就都声明为静态的.

static修饰的方法不需要实例化