简体   繁体   English

Java中的OOP-Android

[英]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: mymethod必须是static方法:

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: 的确,如果mymethod static方法,则也可以像实例方法一样调用它,如下所示:

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? mymethod是仅对类的特定实例有意义的操作吗?

    • Make it an instance (non- static ) method 使其成为实例(非static )方法
  • Is mymethod an operation that does not require an istance to act? mymethod是一项不需要采取任何行动的操作吗?

    • Make it a static method. 使其成为static方法。

It is worth noting that, while they are not the bomb , you should try to avoid static methods whenever possible. 值得注意的是,尽管它们不是炸弹 ,但应尽可能避免使用static方法。 The more you add static methods, the more your OO code turns procedural. 您添加static方法的次数越多,您的OO代码转换成程序性的代码就越多。 Not to mention that static methods are not overridable and, due to that, can be much harder to test/mock. 更不用说static方法是不可替代的 ,因此,测试/模拟可能会困难得多。

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. 这些对象不作用于任何特定对象,因此在调用它们时不会提供任何对象。

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

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