简体   繁体   中英

OOP in JAVA - Android

What would be the most correct way to call a method from another class?

It is more correct to create the object:

private MyClass myclass;
myclass = new MyClass();

Then call a method:

myclass.mymethod();

Or simply call from the class:

MyClass.mymethod();

Which is more advantageous? Which is less costly and less difficult for the system to perform?

Those may not be equivalent.

To be able to call:

MyClass.mymethod();

mymethod must be a static method:

public MyClass {
  public static void mymethod() { /* something */ }
}

It is true that, if mymethod is a static method, you could also call it like an instance method, as in:

myclass = new MyClass();
myclass.mymethod(); // works even if mymethod is static

But, in the end of the day, performance-wise (regarding the method call itself), there's no noticeable difference between the two approaches.

You should choose the approach that makes more sense semantically:

  • Is mymethod an operation that makes sense only to a specific instance of a class?

    • Make it an instance (non- static ) method
  • Is mymethod an operation that does not require an istance to act?

    • Make it a static method.

It is worth noting that, while they are not the bomb , you should try to avoid static methods whenever possible. The more you add static methods, the more your OO code turns procedural. Not to mention that static methods are not overridable and, due to that, can be much harder to test/mock.

You don't really get a choice. You can only do

MyClass.myMethod(); 

if the method was defined as a “class method”:

static void myMethod() {}

Those don't act on any specific object, so you don't provide one when you call them.

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