在不同方法中初始化变量/对象与全局初始化

时间:2014-09-20 08:23:25

标签: java object logic

我想在程序中使用不同功能的对象。

案例1:

class a
{
public Scanner s; //the object
  method1()
  {
   s=new scanner(System.in);
   s.close();
  }

  method2()
  {
   s=new scanner(System.in);
   s.close();
  }
  p s main(String[] args)
 {
  method1();
  method2();
 }

}

案例2:

class a
{
public Scanner s=Scanner(System.in);
  method1()
  {
   //functions with s
  }

method2()
  {
      //functions with s

  } 

  main()
  {
  method1();
  method2();
  }

}

如果我在CASE 1中的一个函数中关闭对象,则无法访问它。 哪种CASE优化?我应该使用哪一个?最初初始化它们会更好吗?

1 个答案:

答案 0 :(得分:0)

我会选择case1

中的解决方案
case 1: 
        class a 
        { 
            public Scanner s; //the object
            method1() 
            { 
                s=new scanner(System.in);
                s.close();
            } 

            method2() 
            { 
                s=new scanner(System.in);
                s.close();
            } 
            p s main(String[] args)
            { 
                method1(); 
                method2(); 
            } 
        } 
    }
相关问题