saurabh ranu
saurabh ranu

Reputation: 1371

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

Upvotes: 0

Views: 2085

Answers (4)

umbr
umbr

Reputation: 440

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.

Upvotes: 1

user425367
user425367

Reputation:

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

Upvotes: 0

Android Killer
Android Killer

Reputation: 18489

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.

Upvotes: -1

Thomas
Thomas

Reputation: 88707

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.

Upvotes: 7

Related Questions