Reputation: 6815
I have below classes.
public class BaseRequest {
protected List<Emp> names; // names property is required in many classes
}
public class FirstRequest extends BaseRequest {
public FirstRequest() {
names = new ArrayList<Emp>();
}
public setNames(List<Emp> names){
super.names = names;
}
public List<Emp> getNames(){
return super.names;
}
}
public class ServiceClass {
public void someMethod(List<Emp> emps) {
FirstRequest request = new FirstRequest();
request.setNames(emps);
//Some Logic
}
}
Am i doing inheritance in right way? how i can i improve it further?
Thanks!
Upvotes: 1
Views: 1982
Reputation: 726479
How i can i improve it further?
Move the methods related to names
into the base class, and make names
private
.
public class BaseRequest {
private List<Emp> names = new ArrayList<Emp>();
public setNames(List<Emp> names){
this.names = names;
}
public List<Emp> getNames(){
return names;
}
}
public class FirstRequest extends BaseRequest {
// the rest of your stuff
}
You should avoid making names
protected: a public getter should be good enough for derived classes and for the other users of the class.
Upvotes: 1
Reputation: 9232
You can convert the BaseRequest
to an interface and provide only the signatures of the methods to be used by the clients. The client should be interested only to the methods provided (api
), not the implementation details Then you can implement them in all classes implement the interface. It is more flexible with an interface:
public interface BaseRequest {
List<Emp> getEmps();
void setEmps(List<Emp> list);
....
}
public class FirstRequest implements BaseRequest{
List<Emp> getEmps(){
return ...;
}
....
}
Upvotes: 0
Reputation: 5802
Depends on what you want to do, for this piece of code most things seem okay. Might want to change
FirstRequest request = new FirstRequest();
to
BaseRequest request = new FirstRequest();
And use getters / setter in the superclass.
Also, in the constructor of the FirstRequest, you should talk to the super class (do the ArrayList initialisation there for example)
public FirstRequest(){
super();
}
and in the super class
public BaseRequest()
{
// initialisation
}
Upvotes: 0