简体   繁体   English

子类实例到超类

[英]Subclass instance to Superclass

How do I create subclass objects, based on an superclass objects? 如何基于超类对象创建子类对象?

eg: 例如:

class Super {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


class Sub extends Super {
    private String lastName;

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}


public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Super sup = new Super();
        sup.setId(1);
        sup.setName("Super");

        Sub sub = new Sub();

        System.out.println(sub.getName());
    }

}

How can I create a 'Sub' object with the properties of a 'Super' created earlier? 如何创建具有先前创建的“超级”属性的“ Sub”对象?

Or should I pass the properties manually, like: 还是应该手动传递属性,例如:

sub.setName(sup.getName());
sub.setId(sup.getId());

you could add a copy constructor to Super Class 您可以将复制构造函数添加到Super Class

public class Super {
    private int id;
    private String name;

    public Super(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public Super(Super other) {
        this.id = other.id;
        this.name = other.name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

and then use this constructor in Sub class 然后在Sub类中使用此构造函数

class Sub extends Super {
    public Sub(Super other) {
        super(other);
    }

    private String lastName;

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

and you can call 你可以打电话

Sub sub = new Sub(sup);

我会在Sub中创建一个静态方法:

Sub.fromSuper(Super s, String last)

I would use apache commons 我会用apache commons

BeanUtils.copyProperties(toBean, fromBean);

I wouldn't add a method to the class itself unless its really needed on every object. 除非确实在每个对象上都需要,否则我不会在类本身中添加方法。 BeanUtils seem appropriate as it appears like something needed only in a specific situation. BeanUtils似乎很合适,因为它看起来只在特定情况下才需要。

In case that you really need the behaviour on every object, than implementing a copy constructor is a way to go 如果确实需要每个对象上的行为,那么实现复制构造函数是一种方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM