Java - 包含变量的抽象类? [英] Java - Abstract class to contain variables?

查看:19
本文介绍了Java - 包含变量的抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让抽象类定义实例变量是个好习惯吗?

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

public abstract class ExternalScript extends Script {

    String source;

    public abstract void setSource(String file);

    public abstract String getSource();
}

子类 ExternalJavaScript.class 然后会自动获取源变量,但我觉得如果所有子类本身定义源而不是继承,那么阅读代码会更容易.

The sub class, ExternalJavaScript.class, would then automatically get the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance.

你有什么建议?

/亚当

推荐答案

我本以为这样的事情会好得多,因为您要添加一个变量,那么为什么不限制访问并使其更简洁呢?你的 getter/setter 应该按照他们在罐头上说的去做.

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;
    }
}

回到问题上来,你有没有在阅读 getter/setter 代码时费心查看它的位置?如果它们都进行获取和设置,那么您在阅读代码时无需担心函数做什么".还有一些其他原因需要考虑:

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:

  • 如果源受到保护(子类可以访问),那么代码就会变得混乱:谁在改变变量?如果它是一个对象,那么当您需要重构时就会变得困难,而方法往往会使这一步变得更容易.
  • 如果您的 getter/setter 方法没有获取和设置,则将它们描述为其他内容.

始终考虑您的课程是否真的与众不同,这应该有助于决定您是否还需要其他课程.

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

这篇关于Java - 包含变量的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆