继承java obj的所有getter / setter方法

时间:2015-04-16 21:55:49

标签: java

我有一个带有许多setter / getter方法的A类,并希望实现一个“扩展A”并提供其他功能的B类。

我无法修改类A,并且它没有将类A obj作为参数的克隆或构造方法。所以基本上我实现了B类,

  • 它有一个构造函数,它将A类obj作为参数并保留此obj的副本

  • 当我们在B上调用setter / getter方法时,它会委托给A类obj

  • 其他功能......

A类有很多setter / getter方法,我觉得这个实现不干净,但不知道如何解决这个问题。通常我可以使B扩展A,但在这种情况下,我必须能够将A类obj作为构造函数的参数。

如果问题不够明确,我很抱歉,如果您需要更多说明,请告诉我。感谢。

示例:

public class A {
    private int x;
    public void setX(int x) { this.x = x; }
    public int getX() { return this.x; }
}

public class B {
    private A a;
    public B(A a) { this.a = a; }
    public void setX(int x) { a.setX(x); }
    public int getX() { return a.getX(); }
    public void foo() { ... };
    public void bar() { ... };
}

基本上A有很多属性X / Y / Z ......并且有很多setter / getters。如果我这样做,那么B有许多虚拟设置器/ getter,只需委托给a上的同一个调用。有更清洁的方法来实现这个吗?

2 个答案:

答案 0 :(得分:0)

如果B类扩展了A类,它将自动继承所有非私有的非静态方法。在您的代码中,A类中的getter / setter被声明为public,因此B类将继承它们。

但是,要实现这一点,您需要重写B类的签名,如下所示,abd删除您在B&B体内编写的所有代码:

public class B extends A {
    // here, put any functionalities that B provides in addition to those inherited from A
}

这样,您可以通过A或B类型的任何引用访问所有getter / setter,如下所示:

public static void main(String... args) {
    A a = new A();
    a.setName("Bob");
    System.out.println(a.getName());

    B b = new B();
    b.setName("Joe");
    System.out.println(b.getName());

    // And even this, thanks to polymorphism :
    A ab = new B();
    ab.setName("Mike");
    System.out.println(ab.getName());
}

答案 1 :(得分:0)

我认为您正在尝试扩展A类的对象以向其添加功能,这就是造成这种困境。您无法使用复制构造函数轻松复制A,因此您尝试使用合成而不是继承,然后才能使用。

三个选项:

  • 做你正在做的事情 - 将A类对象包装成B和委托所拥有的东西 - 它有效并且不太糟糕
  • 使用B的子类A,然后使用某种基于反射的复制例程将所有属性从类型A的对象复制到类型B的新对象中 - 例如http://commons.apache.org/proper/commons-beanutils/ copyProperties函数
  • 在B级创建一个复制构造函数,可以执行您想要的任务

实施例

public class A {
    private int x;
    public void setX(int x) { this.x = x; }
    public int getX() { return this.x; }
}

public class B {
    public B(A a) {
        // copy all A properties from the object that we're going to extend
        this.setX(a.getX());
    }

    .. other stuff
}

您要描述的问题是扩展对象。扩展类很简单 - 只需将其子类化,您就可以使用基本实现和新内容。使用上面的代码扩展对象:

A someA = new A();

// a is initialised as an A

B aWithExtraProperties = new B(someA);

// now you have a B which has the same values as the original A plus
// b's properties
// and as B subclasses A, you can use it in place of the original A

我之前尝试在运行时更改对象的类型并且它感觉不舒服。最好还是考虑一下你为什么要这样做以及是否有替代方案。