【问题标题】:Android Create a class into separate file without new mClass() ...?Android在没有新mClass()的情况下将类创建到单独的文件中......?
【发布时间】:2014-08-24 16:01:27
【问题描述】:

我正在尝试以一种简单的方式处理类,但我无法实现它......

到目前为止...我用它的构造函数和方法创建了一个separateClass.java,但是在Main.java中,我以这种方式调用了separateClass.java的方法...

// 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;
    }

}

【问题讨论】:

    标签: java android class methods


    【解决方案1】:

    将SeparateClass内部的方法设为静态:

    public static String myMethod(String path) {
        ...
    }
    

    然后从您的活动中调用 myMethod,如下所示:

    SeparateClass.myMethod(myPathString);
    

    如果这还不够,您可以在 MainActivity 中导入该方法:

    import static com.mypackage.SeparateClass.myMethod;
    

    然后你可以在没有任何类引用的情况下使用该方法:

    myMethod();
    

    【讨论】:

    • 你的第一个例子有效!但我有问题......我有一个接收字符串值的构造函数,现在我的方法也接收一个字符串......它需要使用静态方法的构造函数?
    • @arickdev 你的方法可以在你的类中设置一个静态字段,然后你的构造函数可以不接收任何参数。
    • 为什么方法应该是静态的?,我读到过,但我很难理解静态的东西! :(
    • @arickdev 如果您想访问类内部的方法而不首先实例化 (new Class()) 该类,则该方法必须是静态的。
    • 好的,我明白了,但是...我还需要构造函数吗?我的代码中有什么需要更正的吗?
    【解决方案2】:

    如果 Main 类扩展 SeparateClass 并且您的方法不是私有的,您可以简单地做到这一点。

    public class SeparateClass {
        public   void myMethod() {
    
    
        }
    }
    
    public class Main extends SeparateClass{
    
        public  void testMethod() {
           myMethod();
    
       }
    

    }

    【讨论】:

    • 谢谢!但是,扩展主类......我不知道......我想要很多单独的类,并扩展它们......它的代码太多了班级名称...但是谢谢! :)
    • 你问过这种可能性,所以我指的是最简单的方法:-)
    • 是的......我以前用过这种方式......它工作!在这种情况下,我需要一个不同的方式......谢谢任何方式! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多