Reputation:
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:
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?
Upvotes: 0
Views: 343
Reputation: 667
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
}
Upvotes: 1