9 April 2008 - Posted in Java

Java - accessing methods from other classes

I am going to show you how to link to methods in other classes in Java

public class ClassName {
private int index;
private String name;

public ClassName() {
index = 0;
name = “Simon”;
}

public void methodName {
// method here
}

}

Now we are going to access a method called otherClassMethodName from the class OtherClass, look at the code in red, this is what you will need to add to your code:

public class ClassName {
private int index;
private String name;
OtherClass otherclass;
// OtherClass is the class name that you want to load and otherclass is the variable name we have assigned to it

public ClassName() {
index = 0;
name = “Simon”;
otherclass = new OtherClass;
// this initialises it and makes it available for use

}

public void methodName {
otherclass.otherClassMethodName();
// This finds and starts the method in otherclass (the variable name for the class otherClass)

}

}

And there you have it the simple tutorial on how to access a method in another class, the only other thing to say is to make sure that you set the method in the otherClass to be public (eg, public void methodName).

keywords: java, accessing another class, accessing methods in another class, connect to other class, get data from another class

Twitter

Leave a Comment