简体   繁体   English

java继承的最佳实践?

[英]java inheritance best practice?

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! 谢谢!

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. 并在超类中使用getters / setter方法。

Also, in the constructor of the FirstRequest, you should talk to the super class (do the ArrayList initialisation there for example) 另外,在FirstRequest的构造函数中,您应该与超类对话(例如,在此处进行ArrayList初始化)

 public FirstRequest(){
 super();
 }

and in the super class 而在超一流

public BaseRequest()
{
// initialisation
}

You can convert the BaseRequest to an interface and provide only the signatures of the methods to be used by the clients. 您可以将BaseRequest转换为接口,并仅提供客户端要使用的方法的签名。 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. 客户端应该只对提供的方法( api )感兴趣,而不对实现细节感兴趣,然后可以在实现接口的所有类中实现它们。 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 ...;
    }

   ....
}

How i can i improve it further? 我如何进一步改善它?

Move the methods related to names into the base class, and make names private . 移动相关的方法names为基类,使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. 您应该避免使names受到保护:对于派生类和该类的其他用户,公共获取者应足够好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM