0

For this problem pretend I am programming a forum. This has two kinds of users: normal users and administrators. Now suppose the forum needs more administrators in orden to optimize the management. However, the new administrators must be picked from the existing regular users. Administrator class inherits from User.

This is what I am struggling to achieve. I have tried both methods showed below but they do not work since the User argument is still a User once it leaves the method.

// First attemp trying casting
public void turnIntoAdminCasting(User u){
    u = (Administrator) u;
}

// Second attemp with constructors
public void turnIntoAdminConstructor(User u){
    u = new Administrator(u);
}

public static void main(String[] args){
    User u = new User();
    User u2 = new User();
    turnIntoAdminCasting(u);
    turnIntoAdminConstructor(u2);
    // Both u and u2 are still User instances
}
Jormii
  • 11
  • 2
    https://stackoverflow.com/questions/4862960/explicit-casting-from-super-class-to-subclass – Tom Stein Jan 06 '18 at 23:40
  • this will not work anyway, because you never return anything, assigning `u =` to something inside the method only affects the reference inside the method, not what is passed in which is a copy of the references. –  Jan 06 '18 at 23:42
  • Your constructor-based approach is close, but you need to take [this fact](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1) into consideration. – Silvio Mayolo Jan 06 '18 at 23:42
  • You need to work with copy constructors, which take copies of the existing fields when constructing a new instance, or make an administrator class own a user. The first approach is is-a, the second has-a relationship. – Dragonthoughts Jan 06 '18 at 23:47

0 Answers0