KKeff
KKeff

Reputation: 348

Java inhertiance of private fields

I know that subclass has no access to private field other than with public setter/getter of super-class. I do not have any experience with object-oriented languages so far. Should I make all fields private and just use public method to access them in sub-classes, or make them protected and use the freely in subclasses and package?

Upvotes: 0

Views: 116

Answers (4)

OPK
OPK

Reputation: 4180

it depends on your needs. If you need access to subclass as well as the same package, make it protected.

Here are the general rules:

private: class access only.

protected: package access and also derived classes.

default: same package only.

public: anyone can access it.

Upvotes: 1

Razib
Razib

Reputation: 11153

In OOP there is a feature encapsulation and encapsulation strongly suggest us to hide data from the outer world. And you can hide data by making field/property/variable private.

And for accessing the private variable use some public getter method.

Upvotes: 1

Murat Karagöz
Murat Karagöz

Reputation: 37584

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

See the Java Tutorial

Upvotes: 0

Michał Szydłowski
Michał Szydłowski

Reputation: 3409

Make them protected. This is the sole purpose why this keyword exists!

Upvotes: 1

Related Questions