JAVA的两个小问题。1,在静态方法中只有使用静态变量或者调用静态方法,但主函数也是静态方法,为什么不

受此限制。2,下面代码中,主方法里,第一种定义是可以的,而第二种会出现错误:无法从静态上下文中引用非静态 变量 this
public class Group
{
private int age;
public class Student
{
String name;
public Student(String n,int a)
{
name=n;
age=a;
}
public Student()
{
name=new String("末知");
age=0;
}
public void output()
{
System.out.println("age:"+age+"name:"+name);
}
}
public void output()
{
Student stu=new Student();
stu.output();
}
public static void main(String[] args)
{
Group st=new Group();//1
st.output();
Group.Student stu=new Group.Student();//2
stu.output();
}
}

【第1个问题】:

你说“在静态方法中只有使用静态变量或者调用静态方法,对于主函数来说不受限制“,那我想问,难道你在主函数main中可以直接调用当前类的成员方法与成员变量?


【第2个问题】:

Student是Group的一个成员内部类,并不是静态内部类。在静态方法main中是无法直接通过new Group.Student()进行实例化的。而是首先将Group进行实现化,然后再才能对Student进行实例化。像这样:

Group st=new Group();
Student student = st.new Student();

或者使用Group匿名对象.new Student()方式:

Group.Student stu=new Group().new Student();

温馨提示:答案为网友推荐,仅供参考
相似回答