为什么不抽象字段? [英] Why not abstract fields?

查看:89
本文介绍了为什么不抽象字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Java类不能像抽象类那样具有抽象字段?

例如:我有两个扩展了相同抽象基类的类.这两个类各自具有相同的方法,但其中包含String常量(恰好是错误消息).如果字段可以是抽象的,那么我可以使这个常量抽象,并将该方法引入基类.相反,我必须创建一个抽象方法(在这种情况下称为getErrMsg()),该方法返回String,在两个派生类中重写此方法,然后可以拉出该方法(现在称为抽象方法). /p>

为什么我不能只将字段抽象呢? Java是否可以设计成允许这样做?

解决方案

您可以通过在抽象类中添加一个final字段来完成您描述的操作,该字段在其构造函数中初始化(未经测试的代码):

abstract class Base {

    final String errMsg;

    Base(String msg) {
        errMsg = msg;
    }

    abstract String doSomething();
}

class Sub extends Base {

    Sub() {
        super("Sub message");
    }

    String doSomething() {

        return errMsg + " from something";
    }
}

如果您的子类忘记"通过超级构造函数初始化最终版本,则编译器将向警告发出错误,就像未实现抽象方法时一样.

Why can't Java classes have abstract fields like they can have abstract methods?

For example: I have two classes that extend the same abstract base class. These two classes each have a method that is identical except for a String constant, which happens to be an error message, within them. If fields could be abstract, I could make this constant abstract and pull the method up into the base class. Instead, I have to create an abstract method, called getErrMsg() in this case, that returns the String, override this method in the two derived classes, and then I can pull up the method (which now calls the abstract method).

Why couldn't I just make the field abstract to begin with? Could Java have been designed to allow this?

解决方案

You can do what you described by having a final field in your abstract class that is initialised in its constructor (untested code):

abstract class Base {

    final String errMsg;

    Base(String msg) {
        errMsg = msg;
    }

    abstract String doSomething();
}

class Sub extends Base {

    Sub() {
        super("Sub message");
    }

    String doSomething() {

        return errMsg + " from something";
    }
}

If your child class "forgets" to initialise the final through the super constructor the compiler will give a warning an error, just like when an abstract method is not implemented.

这篇关于为什么不抽象字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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