Java Android将类创建到单独的文件中,而不使用新的mClass()。。。?
我试图以一种简单的方式处理类,但我无法实现它 到目前为止。。。我用它的构造函数和方法创建了一个separateClass.java,但是在Main.java中,我用这种方式调用了separateClass.java的方法Java Android将类创建到单独的文件中,而不使用新的mClass()。。。?,java,android,class,methods,Java,Android,Class,Methods,我试图以一种简单的方式处理类,但我无法实现它 到目前为止。。。我用它的构造函数和方法创建了一个separateClass.java,但是在Main.java中,我用这种方式调用了separateClass.java的方法 // Current way... separateClass sp = new separateClass(myPathString); String newPath = sp.myMethod(); // The way I would like... String ne
// Current way...
separateClass sp = new separateClass(myPathString);
String newPath = sp.myMethod();
// The way I would like...
String newPath = myMethod(myPathString);
// ADDED AFTER RESPONSE...
// This way helps me when I have more classes (.javas)
String newThig = separateClass.myMethod(myPathString);
String anotherThing = myOtherLibrary.methodForSomeThing(someString);
String numCheck = myCalculations.terrain(altitude, latitude);
// Note: The static way is just recomended with simples processes that don't
// need many objects or constructors.
// so far this is what I understand.
有可能吗?我怎么能做到?
我很感激你的一些想法!:)
已编辑…
public class separateClass{
/* Not needed if static (for novices)
String myPathString;
public Imagen_DirectorioGestor(String myPathString) {
this.myPathString= myPathString;
}
*/
public static String myMethod(String myPathString){
File file = new File(myPathString);
newPath = ...;
return newPath;
}
}
将SeparateClass内的方法设置为静态:
public static String myMethod(String path) {
...
}
然后从活动中调用myMethod,如下所示:
SeparateClass.myMethod(myPathString);
如果这还不够您可以在MainActivity中导入该方法:
import static com.mypackage.SeparateClass.myMethod;
然后您可以在不使用任何类引用的情况下使用该方法:
myMethod();
如果Main类扩展了SeparateClass,并且您的方法不是私有的,则可以简单地执行此操作
public class SeparateClass {
public void myMethod() {
}
}
public class Main extends SeparateClass{
public void testMethod() {
myMethod();
}
}谢谢!,但是,扩展主类。。。我不知道。。。我想有许多单独的类,并扩大所有这些。。。类名中的代码太多。。。但是谢谢!:)你问过可能性,所以我指的是最简单的方式:-)是的。。。我以前用过那种方式。。。它起作用了!,在这种情况下,我需要一个不同的方式。。。无论如何谢谢你!:)你的第一个例子有效!,但我有问题。。。我有一个接收字符串值的构造函数,现在我的方法也接收字符串。。。使用静态方法构造构造函数是必要的?@arickdev您的方法可以在类中设置静态字段,然后您的构造函数就可以不接收任何参数。为什么该方法应该是静态的?我读到了,但我很难理解静态的东西(@arickdev如果您想访问类内部的方法,而不首先实例化(new class())该类,那么该方法必须是静态的。好的,我理解,但是…我仍然需要构造函数?,我的代码中有一些东西需要更正吗?