为什么我不能在公共类的方法之外实例化? [英] Why can't I instantiate outside the method of public class ?

查看:65
本文介绍了为什么我不能在公共类的方法之外实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这个程序来澄清有关getter和setter方法的疑问但是我在下面的代码中提到的line1中遇到了意外错误StackOverflowError:

 < span class =code-keyword> public   class  GetterSetter {
private int a = 10;
GetterSetter gs = new GetterSetter(); // 第1行
static GetterSetter gsr = new GetterSetter(); // 第2行
public int getA(){
return a;
}

public void setA( int a){
this .a = a;
}
public void setB( int b)
{
return ;
}
public int getB()
{
return 1 ;
}
public int check()
{返回 a;}
}
class 检查
{检查c =新检查(); // 第3行
public static void main( String [] args){
GetterSetter gs = new GetterSetter();
gs.setA( 50 );
System.out.println(gs.getA()+ \ n + gs.check());
}
}





有谁可以解释这个问题?很困惑。



我尝试了什么:



我尝试过第2行和第3行,但第2行和第3行都没有错误

解决方案

因为,第1行,每一行在实例化GetterSetter的时候,你实例化一个额外的GetterSetter,它(因为第1行)要求你实例化一个额外的GetterSetter,它实例化一个额外的GetterSetter,等等...... ad无限。



静态行是不同的,因为你只实例化一个在所有实例之间共享的GetterSetter。



For更多关于静态和非静态字段之间的差异,请参阅以下链接中的静态和非静态字段:



http://tutorials.jenkov.com/java/fields.html

I was trying out this program to clarify doubts regarding getter and setter methods but I got an unexpected error "StackOverflowError" in line1 mentioned in below code:

public class GetterSetter {
    private int a=10;
   GetterSetter gs=new GetterSetter();//line 1
   static GetterSetter gsr=new GetterSetter();//line 2
    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
    public void setB(int b)
    {
       return; 
    }
    public int getB()
    {
    return 1;
    }
    public int check()
    {return a;}
}
class Check
{   Check c=new Check();//line 3
    public static void main(String[] args) {
        GetterSetter gs=new GetterSetter();
        gs.setA(50);
        System.out.println(gs.getA()+"\n"+gs.check());
    }
}



Could anyone explain the problem here? Am confused.

What I have tried:

I tried line 2 and 3 but no error in line 2 and also in line3

解决方案

Because, with line 1, every time you instantiate a GetterSetter, you instantiate an additional GetterSetter, which (because of line 1) requires you to instantiates an additional GetterSetter, which instantiates an additional GetterSetter, and so on, and so on...ad infinitum.

The "static" lines are different, because you only instantiate one GetterSetter that is shared between all instances.

For more on the differences between static and non-static fields, see "Static and Non-Static Fields" at the following link:

http://tutorials.jenkov.com/java/fields.html


这篇关于为什么我不能在公共类的方法之外实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆