简体   繁体   English

我可以在抽象类中有私有的final字段吗

[英]Can I have private final fields in abstract class

Can I create a abstract class like below..? 我可以创建如下的抽象类吗?

abstract class A{
private final String    foo;
private final String    too;

public A(final String foo, final String too) {
    this.foo= foo;
    this.too= too;
}
public String getfoo(){
        return foo;
    }
public String gettoo(){
        return too;
    }
}

Short: yes. 简短:是的。

Long(er): an abstract class is just a class that can't be instantiated as is, since parts might still be missing. Long(er):抽象类只是无法按原样实例化的类,因为某些部分可能仍会丢失。 Thus i can have private fields. 因此,我可以拥有私有字段。 Just note that subclasses don't have access to them, except via the getters/setters. 只是请注意,子类无权访问它们,除非通过getter / setter。

Your code is correct. 您的代码是正确的。
Note: good practice in abstract classes is protected constructor, beacuse class itself cannot be instantiated and the inheriting classes must have to call super(...) constructor. 注意:抽象类的良好做法是受保护的构造函数,因为类本身无法实例化,并且继承的类必须必须调用super(...)构造函数。

Yes you can. 是的你可以。

Consider the possibility to make them protected instead of private to allow your subclasses ie the ones extending this class, to have direct access to the fields.. 考虑使它们protected而不是私有的可能性,以允许您的子类(即扩展此类的子类)直接访问字段。

Yes of course possible.But it is not a good practice because you cant create one object of this class.Main point is that you also dont require this type of class because you have not define any abstract functions inside it. 当然可以,但是这不是一个好习惯,因为您不能创建此类的一个对象。要点是您也不需要这种类型的类,因为您没有在其中定义任何抽象函数。 But as per your question you can definitely create this type of abstract class. 但是根据您的问题,您绝对可以创建这种抽象类。

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

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