有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将子类对象与超类对象关联?

我有一个问题,关于如何创建一个新对象,并将其与另一个已经初始化的对象关联,该对象来自java中的父类

更清楚地说,我有一个超类Profile,然后是一个子类Contract,它扩展了Profile,然后是另外两个子类HomePhoneMobilePhone,它们都扩展了Contract

我的菜单有两个选项:

  1. 新档案
  2. 新合同(家庭电话或移动电话合同)

假设用户已经创建了一个没有合同的配置文件,并输入了一些个人信息。我初始化一个Profile对象,然后将其存储到一个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);

在这之前我没事

接下来,假设一个用户已经有了一个配置文件(已经存储在ArrayList中),决定按2键购买一个新合同

我认为最合适的方式是:

Profile c = new MobilePhone();

但我将无法通过这种方式访问相应用户的个人资料

所以我想知道我该如何实现它。我只想根据用户的id将新合同与已经存在的配置文件相关联

有没有关于如何实施的想法


共 (1) 个答案

  1. # 1 楼答案

    下面是一个例子。阅读有关Java创造性设计模式的最佳实践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
    }