java文件中调用函数

java文件中调用函数

本文介绍了Android / Java - 如何在单独的* .java文件中调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我导入完整的包名/ java文件,如果我执行< classname>。< method> ,有时候我可以将它转到访问 - 其他时候我得到很多不能在非静态一堆谈话中使用静态。

I do an import of the full package name / java file, and if I do a <classname>.<method>, SOMETIMES I can get it to access - other times I get a lot of can't use a static in a non static bunch of talk.

我承认我是Java的新手,所以我需要做什么?先调用一个类实例,然后调用我的方法?我对此感到困惑,因为我想将所有'函数'放入一个FunctionsList.java文件中,并将所有主要的Activity(UI)放入MyActivity.java文件中。

I'll admit I'm new to Java, so what do I need to do? Call a class instance first, then call my methods? I'm rather confused by this, as I want to put all of my 'functions' into a FunctionsList.java file, and all of my main Activity (UI) into a MyActivity.java file.

例如:

<MyActivity.java>

import com.example.FunctionsList;

private class MyActivity extends Activity {
  FunctionsList.function();
}

9/10次我得到静态/非静态错误。

9/10 times I get that static/non-static error.

如果我将所有函数都放入MyActivity.java,我就没有问题!有人帮我解决了我认为是基本的Java新手问题吗?

If I put all of my functions into MyActivity.java, I have zero problems! Anyone help me on what I presume is a basic Java newbie issue?

推荐答案

这里有一个例子可以帮助你一点点帮助你。

Here's an example that will hopefully help you out a little.

public class MyFunctionClass {

   public String myFunction() {
      return "This is an instance function.";
   }

   public static String myStaticFunction() {
      return "This is a static function.";
   }

}

然后在你的活动中你有东西像这样。

Then in your activity you have something like this.

public class MyActivity extends Activity {

   @Override
   public void onCreate() {

      // If you want to call your static function, you do not
      // require an instance of a MyFunctionClass object.
      String myStaticString = MyFunctionClass.myStaticFunction();

      // If you want to call your instance function, then you need
      // to create a MyFunctionClass first.
      MyFunctionClass variableName = new MyFunctionClass();
      String myInstanceString = variableName.myFunction();
   }
}

正如Jon所说,你可能会节省一些钱如果你在潜水之前阅读面向对象的编程,会感到沮丧。在潜入之前,新程序员需要了解一些基本的东西。祝你好运!

As Jon mentioned, you'll probably save yourself some frustration if you read up on object-oriented programming before diving in. There are some basic things that a new programmer will need to understand before diving in. Good luck!

这篇关于Android / Java - 如何在单独的* .java文件中调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:48