Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中在一个文件中分别编译两个类?_Java_Oop - Fatal编程技术网

如何在java中在一个文件中分别编译两个类?

如何在java中在一个文件中分别编译两个类?,java,oop,Java,Oop,我在读一本书,它有一个例子,在它的文件中有两个不同类的主要方法,一个主要方法是用于测试目的,但我无法理解如何单独编译类,如果有任何方法,请建议我 这是密码 /** * @author achintya */ public class StaticTest { public static void main(String[] args) { Employee[] staff = new Employee[3]; staff[0] = new Em

我在读一本书,它有一个例子,在它的文件中有两个不同类的主要方法,一个主要方法是用于测试目的,但我无法理解如何单独编译类,如果有任何方法,请建议我 这是密码

/**
 * @author achintya
 */
public class StaticTest
{
    public static void main(String[] args)
    {
        Employee[] staff = new Employee[3];
        staff[0] = new Employee("tom",4000);
        staff[1] = new Employee("dick",60000);
        staff[2] = new Employee("harry",65000);

        for(Employee e : staff)
        {
            e.setId();
            System.out.println("name" + e.getName() + ",id=" + e.getId() + ",salary=" + e.getSalary());
        }
        int n = Employee.getNextId();
        System.out.println("next available id=" + n);
    }
}
class Employee
{
    private static int nextId = 1;
    private String name;
    private double salary;
    private int id;

    public Employee(String n,double s)
    {
        name = n;
        Salary = s;
        id = 0;
    }
    public String getName()
    {
        return name;
    }
    public double getSalary()
    {
        return salary;
    }
    public int getId()
    {
        return id;
    }
    public void setId()
    {
        id = nextId;
        nextId++;
    }
    public static int getNextId()
    {
        return nextId;
    }
    public static void main(String[] args){
        Employee e = new Employee("harry",50000);
        System.out.println(e.getName() + " " + e.getSalary());
    }
}

在您的示例中,在同一个源代码文件中有两个类。 这是完全公平的,因为只有public类需要进入自己的文件。这意味着您可以在同一源代码文件中拥有N个非公共类

当事情被编译后,就不再有“来自同一个.java文件”的概念了

最终得到的是StaticTest.class和Employee.class。JVM只允许您在非公共类上调用
main()
方法


但是:根本没有编译单个类。java编译器的工作原理是“文件粒度”。它将始终编译您提供给它的整个文件,您无法说:编译该文件,但只编译其中的非公共类。

简短的回答是:您不能编译单个类

冗长的答案

您仍然可以单独运行这些类

编译文件时,不会看到任何更改。但是,java将编译两个不同的类,
StaticTest.class
文件中的
StaticTest
,以及
Employee.class
文件中的
Employee

然后,要运行
Employee.class
,只需运行
javaemployee
,就会运行
Employee
的主要方法。阅读更多

下面是cmd命令。它们可以在Linux环境中轻松复制:

C:\...\Folder> javac StaticTest.java
C:\...\Folder> java StaticTest