Java - Abstract class to contain variables?

前端 未结 3 1587
Happy的楠姐
Happy的楠姐 2021-01-03 21:13

Is it good practice to let abstract classes define instance variables?

public abstract class ExternalScript extends Script {

    String source;

    public          


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 21:20

    I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.

    public abstract class ExternalScript extends Script {
    
        private String source;
    
        public void setSource(String file) {
            source = file;
        }
    
        public String getSource() {
            return source;
        }
    }
    

    Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:

    • If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.
    • If your getter/setter methods aren't getting and setting, then describe them as something else.

    Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.

提交回复
热议问题