Which class design is better?

Which class design is better and why?

public class User
{
    public String UserName;
    public String Password;
    public String FirstName;
    public String LastName;
}

public class Employee : User
{
    public String EmployeeId;
    public String EmployeeCode;
    public String DepartmentId;
}

public class Member : User
{
    public String MemberId;
    public String JoinDate;
    public String ExpiryDate;
}

OR

public class User
{
    public String UserId;
    public String UserName;
    public String Password;
    public String FirstName;
    public String LastName;
}

public class Employee
{
    public User UserInfo;
    public String EmployeeId;
    public String EmployeeCode;
    public String DepartmentId;
}

public class Member
{
    public User UserInfo;
    public String MemberId;
    public String JoinDate;
    public String ExpiryDate;
}

The question is simply answered by recognising that inheritance models an "IS-A" relationship, while membership models a "HAS-A" relationship.

  • An employee IS A user
  • An employee HAS A userinfo
  • Which one is correct? This is your answer.


    I don't like either one. What happens when someone is both a member and an employee?


    Ask yourself the following:

  • Do you want to model an Employee IS a User? If so, chose inheritance.
  • Do you want to model an Employee HAS a User information? If so, use composition.
  • Are virtual functions involved between the User (info) and the Employee? If so, use inheritance.
  • Can an Employee have multiple instances of User (info)? If so, use composition.
  • Does it make sense to assign an Employee object to a User (info) object? If so, use inheritance.
  • In general, strive to model the reality your program simulates, under the constraints of code complexity and required efficiency.

    链接地址: http://www.djcxy.com/p/53938.html

    上一篇: Java接口如何模拟多重继承?

    下一篇: 哪个课堂设计更好?