Jonathan Hagen
Jonathan Hagen

Reputation: 732

How to create constructor for generic class (and its subclass) in java

I have two classes one is generic class and other is the sub class of the generic. I am not sure how to create constructors for each class. Here is the example of code:

public class A<T> {
    protected T personInfo;
    protected int age;
    protected String firstName;
    protected String lastName;
    protected int id;
    protected Long port;
    protected String ipAddress;

    public A(T personInfo, int age, String firstName, String lastName, int id, Long port, String 
        ipAddress) {
        this.personInfo = personInfo;
        this.age = age;
        this.firstName = firstName;
        this.lastName = lastName;
        this.id = id;
        this.port = port;
        this.ipAddress = ipAddress;
    }
}

public class B extends A<maleInfo> {
    protected maleInfo personInfo; //not sure if this is necessary

    public B(//do I need this?)
    ...
}

Basically, all of the variables are used by B and B uses maleInfo for generic T. If I create constructor in generic class, intelliJ says "personInfo" in B class might not be initialized. What is the right way to achieve this?

Also, if I create getter/setter for personInfo (generic) in base class, do sub classes still need to create getter/setter for it?

Upvotes: 0

Views: 151

Answers (1)

Stefan Haberl
Stefan Haberl

Reputation: 10539

You don’t need the property, but you’ll need the constructor in your subclass.

The property is inherited (although I would consider protected members a code smell in 99% of the cases), whereas constructors are never inherited in Java.

Your subclass should look like the following:

public class B extends A<maleInfo> {

  public B(maleInfo personInfo, int age, String firstName, String lastName, int id, Long port, String ipAddress) {
    super(...)
  }

}

There are a few more issues with your code:

Classes in Java should always beginn with a capital letter, i.e. MaleInfo instead of maleInfo .

Then as a best practice: Classes should always either be abstract or final. I don’t know your specific use case, but I would look into making A abstract (with a protected constructor) and B final.

And finally: Your code, which operates on your members should go as close as possible to where your members are. So I would suspect, that you want private members instead of protected ones and protected methods in A which operate on these members and could be called from B as well

Upvotes: 1

Related Questions