我在不同的文件中有两个类,我正在尝试从另一个导入一个类。我在想我该怎么做呢?测试类应该接受第一个类中的两个方法并显示它们。我在想我该怎么做呢?
第一个类:
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);
}
}第二个(或测试)类
public class StringUtilsTest {
public static void main(String args[]) {
System.out.println(padLeft);
System.out.println(padLeft);
}
}发布于 2014-02-11 01:01:25
假设这两个类都在同一个包中(从问题的代码看,它们看起来像是在缺省包中),您有几个选择。
第一个选项是显式引用包含padLeft方法的类,如下所示:
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));
}
}如果StringUtils和StringUtilsTest位于不同的包中(对于类及其测试来说不是那么常见),您将需要使用普通的import将StringUtils导入到StringUtilsTest中。
第二种选择是使用这样的import static:
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));
}
}发布于 2014-02-11 01:02:40
在java中,main方法是要运行其余代码的方法。所以你需要做的就是在main中创建一个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"));
}该字符串对象现在可以保存对StringUtils类内部方法调用。为了让这些方法正常工作,您需要像我一样在它们内部传递参数。
注意:如下所示,如果您想要在类StringUtils中定义构造函数,您将使用java类的默认构造函数:
public class StringUtils{
public StringUtils(){
//and in here set the behavior you wish it to have.
}
}希望能有所帮助
https://stackoverflow.com/questions/21683273
复制相似问题