静态方法中只允许访问静态数据,那么,如何在静态方法中访问类的实例成员(即没有附加static关键字的字段或方法)?
在静态方法中不能使用非静态数据或者非静态方法。 其实也不是不能使用,是不能直接使用。我们可以通过类的实例化来做到这个。
package ppt_test;
/*静态方法中只允许访问静态数据,那么,如何在静态方法中访问类的实例成员
(即没有附加static关键字的字段或方法)?*/
public class Test3 {
public int a1=1;
static public int a2=2;
public static void f1()
{
System.out.println("静态方法调用");
}
public void f2()
{
System.out.println("非静态方法调用");
}
public static void main(String args[])
{
Test3 a=new Test3();
System.out.println(a.a1);
a.f1();
System.out.println(a2);
a.f2();
}
}
