Woton Sampaio
Woton Sampaio

Reputation: 456

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?

Upvotes: 1

Views: 211

Answers (2)

acdcjunior
acdcjunior

Reputation: 135762

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 mymethodis a staticmethod, 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.

Upvotes: 4

Bob Jacobsen
Bob Jacobsen

Reputation: 1160

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.

Upvotes: 2

Related Questions