简体   繁体   中英

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. 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 ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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