public class assign { public static void main(String[] args) { int i=10; System.out.println("i="+i); } }如果 main函数是一个静态函数,在静态函数里是不能引用非静态变量的.为什么我写的上面的程序却能正确运行??? 我对static也不太明白。
public static int x=100; test3() { x=500; } public static void main(String[] args){ } } public class test4 extends test3 { public static void main(String[] args){ int x=300; System.out.println("this class"+x); System.out.println(new test4().abc()); } public int abc() { return super.x; } } 总结下来好象如下: 也就是说静态方法不能调用super不知道我的说法对否?
我修改的程序如下: class test3{ int x=100; //这是一个实例变量 public static void main(String[] args){//这是一个静态方法不可以引用x test3 Out = new test3(); Out.out();} public void out(){ //这是一个非静态的方法, System.out.println(x);} //可以引用实例变量x。}public class test4 extends test3{ static int x = 200; //这是一个静态变量 public static void main(String args[]){ //静态方法允许访问静态变量 System.out.println("current class x"+x); test4 hehe = new test4(); hehe.abc(); }public void abc(){ //必须用非静态的方法访问父类 ///的变量实例 System.out.println("super class x"+super.x );}
main函数是一个静态函数,在静态函数里是不能引用非静态变量的.因为静态函数在程序启动后就可以调用(含静态函数的类对象生成之前),而此时,非静态变量还未初始化.换句话说,静态函数就是一个全局性函数,而非静态变量则是一个局部变量,这是不可以的.不知道对不对.
你把super定义成静态的啊。在前面加一个static
{
public static void main(String[] args)
{
int i=10;
System.out.println("i="+i);
}
}如果 main函数是一个静态函数,在静态函数里是不能引用非静态变量的.为什么我写的上面的程序却能正确运行???
我对static也不太明白。
public class test3
{
public static int x=100;
test3()
{
x=500;
}
public static void main(String[] args){
}
}
public class test4 extends test3
{
public static void main(String[] args){
int x=300;
System.out.println("this class"+x);
System.out.println(new test4().abc());
}
public int abc()
{
return super.x;
}
}
总结下来好象如下:
也就是说静态方法不能调用super不知道我的说法对否?
class test3{
int x=100; //这是一个实例变量
public static void main(String[] args){//这是一个静态方法不可以引用x
test3 Out = new test3();
Out.out();}
public void out(){ //这是一个非静态的方法,
System.out.println(x);} //可以引用实例变量x。}public class test4 extends test3{
static int x = 200; //这是一个静态变量
public static void main(String args[]){ //静态方法允许访问静态变量
System.out.println("current class x"+x);
test4 hehe = new test4();
hehe.abc();
}public void abc(){ //必须用非静态的方法访问父类
///的变量实例
System.out.println("super class x"+super.x );}
}
1.静态(static)方法可以只操作静态变量,它们不能访问定义在类或父类中的实例变量。
2.在程序:public static void main(String[] args)
{
int i=10;
System.out.println("i="+i);
}
中,main方法是定义了一个实例变量i,而不是去引用(访问)它,如果i是定义在main方法程序段外,则main方法是不可访问到i的。