John
John

Reputation: 961

Android / Java - How do I call upon a function in a separate *.java file?

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.

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.

For example:

<MyActivity.java>

import com.example.FunctionsList;

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

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

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?

Upvotes: 5

Views: 16927

Answers (2)

bporter
bporter

Reputation: 4537

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();
   }
}

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!

Upvotes: 16

Jon Skeet
Jon Skeet

Reputation: 1500535

If you want to use a non-static method, you have to have an instance of the class to call the method on. If you want to use a static method, you don't need an instance.

As an example, suppose you tried to call String.length() - what could that return? It's trying to find the length of something, but you haven't specified which string you're interested in. The same is true for other instance methods - the results will usually depend on which object you're calling them on, which is why they're instance methods to start with.

As an aside, I would strongly recommend you to learn the basics of Java first, before trying to use Android. That way when you get into genuinely tricky problems, you won't have to wonder whether it's part of Android or whether it's a simple Java error. See my answer on a related question for more advice about this.

Upvotes: 3

Related Questions