0

I got 2 POJOs that are being passed to a HttpEntity and converted to json.

Before passing them i need a variable which is in both of the POJOs with different names because of the needs of the API so i cant change them.

What is the best way without casting and in terms of OOP also within the POJO definition like mentioned in Wikipedia?

Abstract pojo

public abstract class Pojo{

//some common variables
//setter getters

}

PojoOne

public class PojoOne extends Pojo{

private String id;

//setter getter for id

}

PojoTwo

public class PojoTwo extends Pojo{

private String identifier;

// setter getter for identifier
}

Class that

public class SomeOtherClass {

public void getIdForUse(Pojo pojo){

String s = pojo. // How should this be to have ability to get both id and identifier

}

}

yavuzd
  • 13
  • 2
  • In abstract class `Pojo` define abstract method `getId()` and realize it in both child classes. – sanluck Apr 02 '16 at 06:35
  • So then call `getId()` from `Pojo` in `SomeOtherClass`. – sanluck Apr 02 '16 at 06:35
  • The downside of it is every child pojo created in the future would have to override getId() even if they don't have an id or identifier. – yavuzd Apr 02 '16 at 06:40
  • Yes, it is. You can `return null;` for example in this cases. – sanluck Apr 02 '16 at 06:42
  • @YavuzDoğan Then getIdForUse() shouldn't take a Pojo as argument, but a more specific class or interface which provides a getId() method, since it NEEDS its argument to have an ID. – JB Nizet Apr 02 '16 at 06:43

1 Answers1

0

Add a common method to the common superclass:

public abstract class Pojo {

    public abstract String getId();

    // some common variables
    // setter getters
}

public class PojoOne extends Pojo {

    private String id;

    @Override
    public String getId() {
        return id;
    }

    //setter for id
}

public class PojoTwo extends Pojo {

    private String identifier;

    // setter getter for identifier

    @Override
    public String getId() {
        return identifier;
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255