Java 试着一起上课

Java 试着一起上课,java,Java,我正在研究学习java,我对代码有点问题 我有一个叫做apples的类,它定义了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()

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

我有一个叫做apples的类,它定义了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);
    }

}
然后我有一个被称为Called working with 2ndClass的类,它应该与Apple类一起工作

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

我想做的是看看类是如何一起工作的,但是调用printit函数的行在某种程度上不起作用,这是为什么?

使用2ndClass中的main方法不调用Apple类中的main方法。因此,当调用printit()方法时,a、b和c没有初始化(即它们没有值)

我认为您想要的是使用一种构造函数方法,如下所示:

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程序时,只调用一个主方法(entry类的主方法)。这意味着,因为Apple没有main方法,所以必须在workingWith2NDclass中调用main方法

因此,您现在将程序编译为

javac workingWith2NDclass.java
并运行它

java workingWith2NDclass

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

public class workingWith2NDclass {
    public static void main(){
        apples aMethod = new apples();
        aMethod.printit();
    }
}
您应该在entry方法中将“String[]args”作为参数。这些是通过命令行启动程序时指定的参数

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

您可能正在执行的是
apples.main
,而不是
处理2ndclass.main
。预期的输出是什么?您将获得什么?如何运行程序?“行不通”是什么意思?你有错误吗?如果是的话,请把它寄出去。在Java中,通常以大写字母开头类名。我建议您学习两个主题:1)构造函数和2)静态和非静态方法之间的区别。错误:在类learnJava.apples中找不到Main方法,请将Main方法定义为:public static void Main(String[]args)args有什么用途?它是什么意思?它的用途是什么?字符串[]是用于通过命令行启动程序的参数。如果您将程序打包到一个jar中,您可以这样做,通过命令行启动它:
java-jar TestProgram.jar apples cookies turtles
字符串[]现在看起来像['apples','cookies','turtles'。