试图一起上课

时间:2014-08-12 23:00:58

标签: java

我正在研究学习java,我对代码有点问题。

所以我有这个叫做苹果定义3个字符串的类

public class apples {

    public static String a,b,c;

    public static void main(String[] args){
        a = "its an a";
        b = "its an b";
        c = "its an c";

    }
    public void printit(){
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }

}

然后我有这个被称为workingWith2NDclass的类,它应该与苹果类一起工作

public class workingWith2NDclass {
    public static void main(){
        apples aMethod = new apples();
        aMethod.printit();
    }
}

我想要做的是看看班级如何一起工作,但是稍微调用printit函数的行不会起作用,为什么会这样?

2 个答案:

答案 0 :(得分:2)

不幸的是,我没有代表对子帖发表评论,但你在这里有错误:

public class workingWith2NDclass {
    public static void main(){
        apples aMethod = new apples();
        aMethod.printit();
    }
}

你应该在entry方法中将'String [] args'作为参数。这些是通过命令行启动程序时指定的args。

public class workingWith2NDclass {
    public static void main(String[] args){
        apples aMethod = new apples();
        aMethod.printit();
    }
}

答案 1 :(得分:1)

workingWith2NDclass中的main方法不会调用apples类中的main方法。因此,当调用printit()方法时,a,b和c不会被初始化(即它们没有值)。

我认为您想要的是使用 contructor 方法,如下所示:

public class apples {
    public static String a,b,c;
    // This method contructs the appls class, to be used by others. It initializes the a, b, and c members.
    public apples(){
        a = "its an a";
        b = "its an b";
        c = "its an c";
    }
    public void printit(){
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}

运行java程序时,只调用一个main方法(条目类的方法)。这意味着,因为apple没有main方法,所以你必须在workingWith2NDclass中调用它。

所以你现在编译你的程序

javac workingWith2NDclass.java

并使用

运行它
java workingWith2NDclass