Reputation: 3
I have two classes in separate files and I'm trying to import one class from the other. I was wondering how I could go about doing that? The the test class is supposed to take both methods from the first class and display them. I was wondering how I would go about doing that?
The first class:
public class StringUtils {
public static String padLeft(String orig, int n) {
orig = "testing for lab06";
return String.format("%1$-" + n + "orig", orig);
}
public static String padLeft(String orig, int n, char c) {
return String.format("%1$-" + n + c + "orig", orig);
}
}
The second (or test) class
public class StringUtilsTest {
public static void main(String args[]) {
System.out.println(padLeft);
System.out.println(padLeft);
}
}
Upvotes: 0
Views: 102
Reputation: 34301
Assuming both classes are in the same package (it looks like they're in the default package from the code in the question) you've got a couple of options.
The first option is to explicitly refer to the class containing the padLeft
method like this:
public class StringUtilsTest
{
public static void main(String args[])
{
System.out.println(StringUtils.padLeft("test 1", 5));
System.out.println(StringUtils.padLeft("test 2", 5));
}
}
Had StringUtils
and StringUtilsTest
been in different packages (not that usual for a class and its test) you would have needed to import StringUtils
into StringUtilsTest
with a normal import
.
The second option is to use a import static
like this:
import static StringUtils.padLeft;
public class StringUtilsTest
{
public static void main(String args[])
{
System.out.println(padLeft("test 1", 5));
System.out.println(padLeft("test 2", 5));
}
}
Upvotes: 1
Reputation: 1820
In java the main method is the one that is going to run the rest of the code. So what u need to do is inside the main create an object of type StringUtils:
public class StringUtilsTest{
public static void main(String[] args){
StringUtils str = new StringUtils();
System.out.println(str.padLeft("random string",5));
System.out.println(str.padLeft("random string",5,"c"));
}
that str object now can hold the calls to the methods inside StringUtils class. For the methods to work properly you need to pass the arguments inside them like i did.
Note: Like this you are using the default constructor for java classes if you want to define the constructor you have to do in the class StringUtils the following:
public class StringUtils{
public StringUtils(){
//and in here set the behavior you wish it to have.
}
}
Hope it helps
Upvotes: 0