Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

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.

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. 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.

I'm at a loss here, any recommendations are greatly appreciated.

like image 889
Shaded Avatar asked Jan 22 '26 23:01

Shaded


1 Answers

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. Therein, you can parse the ResultSet and set the object's fields.

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.

like image 190
mre Avatar answered Jan 25 '26 12:01

mre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!