我有两个类,Person
和 Employee
。 Employee
扩展了 Person
。
我有一个从存储中读取 Person
的方法,并且正在编写读取 Employee
的方法。
我想重用 Person
的方法来读取与 Employee
相同的属性,而无需复制粘贴代码,但是可以'似乎没有找到一种方法来做到这一点。
public Person getPersonFromStorage() {
Person person = new Person();
// ... logic
return person;
}
public Employee getEmployeeFromStorage() {
Employee employee = new Employee();
// ... logic for employee-specific fields
// I want to read the fields inherited from Person here
return employee;
}
我无法转换从 getPersonFromStorage
检索到的 Person
,因为它不是 Employee
。可能是,因为它也不是另一种子类型,但事实并非如此。
我可以执行以下操作:
public Person getPersonFromStorage(Person person) {
if(person==null) { person = new Person(); }
// ... logic
return person;
}
public Employee getEmployeeFromStorage() {
Employee employee = (Employee) getPersonFromStorage(new Employee());
// ... logic for employee-specific fields
return employee;
}
但如果可以的话,我想避免这种复杂性。我感觉我忽略了一些基本的东西。有没有更好的方法来解决这个问题?
最佳答案
只是提供一个我通常在这个实例中使用的不同架构。如果您谈论“来自存储”,对我来说这意味着某种持久结构。文本文件、数据库等。对于以下示例,我们假设您的值位于文本文件中。
假设一个文件employees.txt
,其中包含一名员工:
// Dave's person details.
Dave
Manchester
32
// Dave's employee details
Assassin
Mostly North Korea.
然后你就有了一个Person
类,看起来有点像这样:
public class Person
{
private String name;
private String location;
private int age;
public Person(String name, String location, int age)
{
// blah blah blah.
}
}
还有一个类Employee
,如下所示:
public class Employee extends Person
{
private String jobTitle;
private String area;
public Employee() {
// etc.
}
}
在 Person
类中,您可以创建一个旨在读取 Person
参数的构造函数。像这样的东西:
public Person(Scanner file)
{
this.name = file.nextLine();
this.location = file.nextLine();
this.age = file.nextInt();
file.nextLine(); // Make sure you're pointing at the new line!
}
在您的 Employee
类中,您可以创建一个构造函数,旨在读取员工的参数,同时调用它的父类(super class)来处理其他值。
public Employee(Scanner file)
{
super(file);
this.jobTitle = scanner.nextLine();
this.area = scanner.nextLine();
}
然后你所要做的就是调用它:
Scanner s = new Scanner("employees.txt");
Person p = new Employee(s);
或者使其更紧凑:
Person p = new Employee(new Scanner("employees.txt"));
这将解析文件,并返回一个对象,同时包装需要数据的类中实际读取文件的所有逻辑。
不是文本文件?
嗯,这并不重要。重要的是只是在调用链中传递一个对象,并且这些方法正在执行特定类需要执行的操作,然后传递该对象。如果是数据库行
,原理是完全一样的。
关于java - 用作子类型时可用的父类(super class)型的单个 'load from datastore' 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19228246/