Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

java - Subclass extending the same superclass using another subclass within itself

The schema is like below

{
   id
   name
   surname
   employees {
      id
      name
      surname
   }
}

I was wondering if its oop representation could be

class Person {
   id
   name
   surname
}

class Employee extends Person {}

class Supervisor extends Person {
   List<Employee> employees;
}

So two classes will be inherited from the same class but one of them uses the other one within it self.

If this is not a good idea, what would be a better way of constructing this schema.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no inherent issue, in a language or OO sense, with Employee and Supervisor having a common superclass, and one depending on the other as well.

There is, however, a possible issue with the suitability of that approach for modelling your particular problem domain. In common English, most "supervisors" also have their own supervisors, and all supervisors, even the topmost, are ordinarily considered "employees" as well. Additionally, it is unclear whether your Person class serves any useful purpose: if all supervisors are also employees, then does your model need to accommodate any Persons who are not employees? It's not clear that it even makes sense to use different classes to distinguish between employees who are supervisors and those who are not.

My first inclination would be to go much simpler:

class Employee {
    int id;
    String name;
    String surname;
    List<Employee> employees;
}

Employees who are not supervisors would just have an empty employees list. And before you ask, no, it is not a problem for Employee to contain a List<Employee>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...