1

Can we achieve hierarchical inheritence in java, I've a scenario something like this

class Person {
     String name;
     int age;
     List<Address> addressList;
     
     // ... getters, setters
}
class Address {
    String state;
    String contry;
    // ... getters, setters
}

class ExtendedAddress extends Address {
    String street;
    // ... getters, setters
}

class ExtendedPerson extends Person {
    String occupation;
    List<ExtendedAddress> addressList;
    // ... getters, setters
}

But in the ExtebdedPerson class, the getters and setters give errors as their return type changes..

here either I need to change the name of addressList or manually write setter and getter logic.

I'll not be able to because these DTOs are generated by swagger..

Is there an approach I can follow here? Or, Is there a way I can write my swagger yaml more effectively.

This is my swagger definition

Person:
  type: object
  properties:  
     name:
      type: string 
      description: "Name of the person"
     age:
      type: integer
      description: "Age of the person"  
     addressList:
      type: array
      description: "Address List"
      items:
       $ref: '#/definitions/Address' 
 Address:
  type: object
  properties:  
     state:
      type: string 
      description: "Name of the state"
     country:
      type: string 
      description: "Name of the country"
      
 ExtendedAddress:
  allOf:
    - $ref: '#/definitions/Address'
    - type: object
  type: object
  properties:  
     street:
      type: string 
      description: "Name of the street"

 ExtendedPerson:
  allOf:
    - $ref: '#/definitions/Person'
  type: object
  properties:  
     occupation:
      type: string 
      description: "Name of the occupation"
     addressList:
      type: array
      description: "Address List"
      items:
       $ref: '#/definitions/ExtendedAddress' 

1 Answers1

1

You can't override getAddress in that way.

The reason is that in Person you have said that getAddress returns a List that can take any kind of Address (Address itself or any class extending it).

However, in ExtendedPerson, you are trying to redefine getAddress saying that the List can now only contain ExtendedAddress objects. So ExtendedPerson can't fulfil the contract defined by Person.

For example: if I created another subclass of Address, say DeliveryAddress extends Address, I would be allowed to add DeliveryAddress objects to the List in Person but I would not be allowed to add them to the List from ExtendedPerson. Therefore ExtendedPerson cannot extend Person.

You will have to create a separate getter method or re-use the same one and cast the result.

rghome
  • 8,529
  • 8
  • 43
  • 62