简体   繁体   English

为子类设置超类属性

[英]Setting super class properties for subclass

So I'm having a bit of an issue getting my properties to set properly in a super class type scenario. 所以我有一个问题让我的属性在超类类型场景中正确设置。

I have 2 classes such that class B is a specialized version of class A, let's say... 我有2个班级,因此B班是A班的专业版,让我们说......

public class A {
    private String name;
    private int id;
    ...
} 

public class B extends A {
    private Date time;
    private int status;
    ...
}

Now what I'm trying to do is use a method that is used to set properties in A from a result set, but instead set them in an instance of B. 现在我要做的是使用一个方法,用于从结果集中设置A中的属性,而是将它们设置在B的实例中。

public A setProperties(ResultSet rs) {
    A a = new A();
    a.setName(rs.getString(...));
    ...
    return a;
}

I have tried taking the return from this and casting it as a B, but of course not all A's are B's... so that doesn't work. 我试过从这里拿回来并把它作为B投射,但当然不是所有的A都是B的......所以这不起作用。 I have also tried adding another parameter to the setProperties method so that it takes in an A and returns an A, that way I can use polymorphism to get my B back, but then all my values were nulled out. 我还尝试在setProperties方法中添加另一个参数,以便它接收A并返回A,这样我可以使用多态来获取我的B,但随后我的所有值都被清空了。

I'm at a loss here, any recommendations are greatly appreciated. 我在这里不知所措,任何建议都非常感谢。

Declare the method in the superclass. 在超类中声明方法。 The subclass will override this method and then invoke super.foo(ResultSet rs) , where foo(...) is the overridden method. 子类将覆盖此方法,然后调用super.foo(ResultSet rs) ,其中foo(...)是重写方法。 Therein, you can parse the ResultSet and set the object's fields. 在其中,您可以解析ResultSet并设置对象的字段。

Example - 示例 -

class Foo{
    void setProperties(final ResultSet rs){
        // do stuff
    }
}

final class Bar extends Foo{
    @Override
    final void setProperties(final ResultSet rs){
        // do stuff
        super.setProperties(rs);
    }
}

For more information, see Using the Keyword super . 有关更多信息,请参阅使用关键字super

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

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