跨多个文件创建对象(Java)

时间:2014-03-25 03:17:36

标签: java object multiple-files

所以我有2个名为Employee.java和Write.java的文件(这两个文件在同一个包中)。在Employee.java中说我有

public class Employee {
    private String firstName = "test";
    private String lastName = "ing";

    public Employee(String first, String last) {
        firstName = first;
        lastName = last;
    }

    public Employee(Employee copy) {
        firstName = copy.firstName;
        lastName = copy.lastName;
    }
}

然后在我的Write.java中,我想创建一个名为tempee的Employee类型的对象。像

public void obtainInfo(Employee temp) {
    String firstName = temp.firstName;
    String lastName = temp.lastName;
}

但是我收到一个错误,告诉我它找不到行中的符号。

public void obtainInfo(Employee temp) {

我只是想知道我哪里出错了,我无法在不同的文件中创建一个对象。尽管他们在同一个套餐中我无法访问它们?

我希望稍后能够将其合并以帮助我通过读取数组列表来构建文本文件,但我想首先从一个对象中读取一行。

2 个答案:

答案 0 :(得分:0)

确保Write.java的类具有与Employee(IE:Public)相同的访问级别。如果这不是问题,我会专门展示来自Write.java的代码,因为这很可能是问题来自的地方。

答案 1 :(得分:0)

在我看来,您正在尝试设置一些内容,以便您可以复制一个Employee,并能够将属性写入文本文件。这不会写入文本文件,但我认为它可能会清除一些事情。

public class Employee {
    private String firstName;
    private String lastName;

    public Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Employee(Employee copy) {
        firstName = copy.firstName;
        lastName = copy.lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Employee");
        sb.append("{firstName='").append(firstName).append('\'');
        sb.append(", lastName='").append(lastName).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

TestClass.java

public class TestClass {

    public static void main(String[] args){
        //First we have to have one to copy
        Employee emp = new Employee("Joe", "Dirt");

        //Now we have a copy
        Employee emp2 = new Employee(emp);

        //Calls the Employee.toString() method and sends it to System.out
        System.out.println("Employee 1 : " + emp);
        System.out.println("Copy of Employee 1 : " + emp2);
    }
}