简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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