0

I have a question on how I can create a new object and associate it with another already initialized object from its parent class in java.

To be clearer, I have a superclass Profile, then a subclass Contract which extends Profile and then two other subclasses HomePhone and MobilePhone that both extend Contract.

Two of the options of my menu are:

  1. New profile.
  2. New contract(HomePhone or MobilePhone contract).

Suppose that the user has already created a profile without a contract and has entered some personal information. I initialize a Profile object and then i store it to an ArrayList.

Profile p = new Profile();
/*
Promt the user to enter his information
and when he has finished add the object to the array list.
*/ 
profiles.add(p);

I'm okay until here.

Next suppose that a user who has already a profile (which is already stored in the ArrayList), decides to press 2 to buy a new contract.

I think that the most appropriate manner to do this is :

Profile c = new MobilePhone();

But I will not have access to the appropriate user's profile in that way.

So I wonder how could I implement it. All I want is to associate the new contract with an already existed profile based on an id of the user.

Any ideas on how to implement it?

  • Can you not do new MobilePhone(existingProfile), in turn, call the constructor chain and initialize a profile using the existing profile? – Tushar Nov 30 '20 at 18:19
  • I'm going to try it. Thanks for your time! –  Nov 30 '20 at 18:20
  • Does this answer your question? [Create instance from superclass instance](https://stackoverflow.com/questions/6924974/create-instance-from-superclass-instance) – tevemadar Nov 30 '20 at 18:38
  • That was a good help, but not exactly what im looking for. Thanks for your time though! –  Nov 30 '20 at 18:49

1 Answers1

1

Here is an example. Read about Java Creational design pattern for best practices. https://www.baeldung.com/creational-design-patterns

public class Parent {
    private String parentProperty;

    public Parent(final String parentProperty) {
        this.parentProperty = parentProperty;
    }
//getter and setters
}


public class Child extends Parent {
    private String childProperty;

    public Child(final String parentProperty, final String childProperty) {
        super(parentProperty);
        this.childProperty = childProperty;
    }
    public Child(Parent p, final String childProperty) {
        super(p.getparentProperty());
        this.childProperty = childProperty;
    }
//getter and setters
}
Tushar
  • 670
  • 3
  • 14