bubblebath
bubblebath

Reputation: 999

Java setting the super extended class from the a passed in object

I have a class like this

public class User implements UserInterface, Parcelable
{
    public User(int userID, String firstName, String lastName, String mobileNumber, Date dateAccountCreated)
    {
        this.userID = userID;
        this.firstName = firstName;
        this.lastName = lastName;
        this.mobileNumber = mobileNumber;
        this.dateAccountCreated = dateAccountCreated;
    }
}

And I then have another class that extends into this:

public class Invitee extends User
{
    private int eventDescision; 
    public Invitee(User u, int eventDescision)
    {
        super() = u;
        this.eventDescision = eventDescision;
    }
}

Obviously this line super() = u; does not work. However, how can I achieve the this functionality where I pass the User object the invitee recieves and set it as the extended object without having to create another constructor? I know I can just the object as a variable with a getter and setter, however, I like the way it flows without doing this as and invitee is always user.

Upvotes: 1

Views: 1682

Answers (4)

KonradOliwer
KonradOliwer

Reputation: 166

You can:

  1. Use decorator design patter in Invitee
  2. Define costructor User(User u)
  3. as people manthioned before: use super() with all parameters

Remember that super is calling constructor of superclass, so you can't call constructor which is not defined.

Upvotes: 0

Mena
Mena

Reputation: 48404

You cannot automatically pass an instance of the base class to the base class' constructor call (super) in the child class' constructor.

What you might want to do is pass the base class' properties in the super call.

For instance is User properties are not private:

public Invitee(User u, int eventDescision) {
  super(u.userID, u.firstName, u.lastName, u.mobileNumber, u.dateAccountCreated);
...

Upvotes: 0

logoff
logoff

Reputation: 3446

User you receive in Invitee constructor is a real instance and you are creating another one. You can not assign one instance in a super constructor, you only can copy it, with a copy constructor.

Upvotes: 4

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

It should rather be:

super(u.getUserID(), 
      u.getFirstName(), 
      u.getLastName(), 
      u.getMobileNumber(), 
      u.getDateAccountCreated());

Upvotes: 1

Related Questions