开发者

Can I have private final fields in abstract class

开发者 https://www.devze.com 2023-04-02 00:23 出处:网络
Can I create a abstract class like below..? abstract class A{ private final Stringfoo; private final Stringtoo;

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(){
     开发者_如何学C   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. Thus i can have private fields. Just note that subclasses don't have access to them, except via the getters/setters.


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.


Yes you can.

Consider the possibility to make them protected instead of private to allow your subclasses i.e. the ones extending this class, to have direct access to the fields..


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消