How to declare same variable in both super class and subclass

Viewed 41

Parent class

@Getter
@Setter
public class BaseChapter {
  protected String chapterId;
  private List<BaseSection> sections;
}

**Child class **

@Getter
@Setter
public class Chapter extends BaseChapter {
  private Integer title;
 private List<Section> sections; 
}

I'm using springboot and java 11 ,I need to use sections variable in both baseChapter and Chapter class I use both classes in two diffrent APIs.but i got error when doing this.how to overcome this problem

1 Answers

I will assume that the problem is, you want to override the type of this list, not have two different lists.

In that case I would propose to use generics:

superclass

@Getter
@Setter
public class BaseChapter <T extends BaseChapter> {
  protected String chapterId;
  private List<T> sections;
}

subclass

@Getter
@Setter
public class Chapter extends BaseChapter<Chapter> {
  private Integer title;
}
Related