【问题标题】:Is it possible to get terminal input in init()?是否可以在 init() 中获取终端输入?
【发布时间】:2015-05-09 20:24:54
【问题描述】:

我有这个代码:

public class test {

    init() {
        //How can i get access of args?
    }

   public static void main(String[] args) {
        new test();
}

如何在init() 中获取“args”的访问权限?

【问题讨论】:

标签: java terminal init


【解决方案1】:

只需将其作为参数传递即可。

public class test{

    init(String[] args){
     //How can i get access of args?
    } 

   public static void main(String[] args) {
        test t = new test();
        t.init(args);
    }
}

记住,你应该把你的类名大写。

【讨论】:

  • 问题是我需要 init() 中的 args。当我写 test t = new test();启动初始化,当时我没有 args
【解决方案2】:

在类中定义一个实例字段,并创建构造函数来接受数组并设置字段:

   public class test{

       String[] args;

       public test(String[] args){
           this.args = args;
       }
       init(){

       }
   } 

   public static void main(String[] args) {
       new test(args);
   }

或者将它作为参数传递给方法。

init(String[] args){

}

如果init 需要test 类中的任何内容,则必须创建该类的实例

test t = new test();
t.init(args);

如果init 不需要新的测试实例(例如不访问任何实例变量或方法),您可以将 init 定义为静态并直接调用该方法:

static init(String[] args){//method declaration

}
public static void main(String[] args) {
   test.init(args);//call the method in a static way
}

【讨论】:

  • init 在我的构造函数之前运行:/ 所以我试过这个
  • init 目前定义为实例方法,因此必须先调用构造函数。 init 是否依赖于 test 中的任何内容 - 例如,您可以将 init 定义为静态吗?
  • 我不能像现在这样使 init 成为静态的。当您创建“测试”对象时,有什么方法可以直接将参数传递给 init() ?
  • Is there any way to pass directly a argument, when u create a object of "test", to init() 是的,因为我的回答的第一部分建议将数组传递给构造函数。如果从构造函数调用init,那么只需将构造函数参数传递给init
猜你喜欢
  • 2020-04-18
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多