简体   繁体   English

从另一个没有构造函数的类中使用Method

[英]Use Method from another class without constructor

I'm trying to use a method from another class, but I think I can't really use the constructor here is the first class : 我正在尝试使用另一个类中的方法,但是我想我不能真正使用构造函数,这里是第一个类:

public class Rules {
    public Rules(int size) {
        //body
    }

    public void methodINeed() {

    }
}

and I want to use the method in it in my second class, but since if I use the constructor I have to give an int, which basically screws up my calculations, i'm left with no idea of what to do, what are my possibilities here? 并且我想在第二个类中使用该方法,但是由于如果使用构造函数,我必须给出一个int,这基本上弄乱了我的计算,我不知道该怎么做,我该怎么办这里的可能性?

just make another empty constructor: 只需创建另一个空的构造函数即可:

public class Rules{
  public Rules(int size){
    //body
  }

 public Rules()
 {
    //body
  }

  public void methodIneed(){

  }
}

Then to access the method you need, 然后访问所需的方法,

Rules x = new Rules();
x.methodINeed();

You can access methods of other classes without contructing them if you declare those methods static: 如果将其他方法声明为静态,则可以访问其他类的方法而无需构造它们:

public class Rules{
  public Rules(int size){
    //body
  }
  public static void methodIneed(){

  }
}

I think you have to review the design of your classes why in the earth you have to call a method in other class for calculations purpose ??? 我认为您必须回顾类的设计,为什么在地球上您必须调用其他类中的方法以进行计算?

possible solution: 可能的解决方案:

  • mix two classes 混合两节课
  • add third class ( for instance Helper class) and call HelperClass.calculateForMe(sth) 添加第三类(例如Helper类)并调用HelperClass.calculateForMe(sth)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM