Java inhertiance of private fields - java

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?

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

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.

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.

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

Related

Access Modifier of top class and class member [duplicate]

I wonder if it's okay (not considered bad practice) to have public members in package private class. I tend to add public keyword to members of my default visibility classes to indicate that such members are part of the classes API.
I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (i.e. package visibility). Is that correct?
Example:
class ModuleImplementationClass {
private int fieldA;
private String fieldB;
private void someClassInternalMethod() {
// impl
}
public int doSth() {
// method that will be called by other classes in the package
}
}
I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (i.e. package visibility). Is that correct?
Well that depends. Not if you're overriding existing methods (e.g. toString()) or implementing an interface.
If you don't want the method to be used from outside the package, make it package private. If you're happy for it to be used from anywhere, make it public. Or another way to think about it: design your method access so that if someone changed just the class access to make it a public class, you wouldn't want to change the method access too.

Java abstract class - Should the instance variables be private or protected?

Should the instance variables be private or protected in java abstract class?
Simple question. I am trying to get more insight into the concept of abstraction in java.
Thanks!
As a rule of thumb, go for non-final private variables. If your design calls for giving derived classes access to these variables, provide protected methods for accessing them.
Using protected variables creates maintenance liability in all classes, abstract or not. As soon as someone inherits from your abstract class, your protected variables become exposed as if they were public. Here are some reasons why this variables should be avoided:
Inheriting classes can change your variables at will - this may go around variable validations set up by the abstract base class
Inheriting classes become dependent on variable names and types - this locks in the design choice that you made when defining protected variables.
First rule does not apply to final variables because they cannot be changed, so the rule makes an exception for them. Second rule still applies, though, so you should be careful about defining protected variables, even in situations when they are final.
If protected then this class and any subclasses may access the property. If private then only this class may access the property (it is not inherited). It depends on if you need to access them in any subclass.

Confusion on when to use private vs protected fields

I have seen users in SO saying that protected fields are bad, because it can introduce problems as the code grows. Please refer to the following code.
public class Car {
private String modelName;
private int yearReleased;
//getters and setters
}
If the Car class is extended by a class named ToyotaCar
public class ToyotaCar extends Car{
// Toyota specific stuff
}
I want my ToyotaCar object to have a modelName and yearReleased fields. And that is why I decided to extend from Car class. But private members are not inherited by the subclass (even though I could access those fields using a public getter and setter). Now my confusion is whether I should make the fileds in the Car class to protected instead of private. But people say that introduces problems.
Does it mean no matter what class you write always, make the fields private?
If so on what instances the protected keyword is used? is it only for methods which we are planning to use in our subclasses?
You nailed it yourself: a good practice is to make everything 'private' by default. Then, your specific design may require for example to be able to use some attributes or (preferably) some methods inside a subclass. In that situation, you'll need to move them toward 'protected' - but only in that situation.
Remember that using the accessors (getters & setters) is perfectly ok, and can be done without breaking encapsulation.
If there is a strict urgency(due to a specific design/pattern) of changing the fields from the subclass, then you should go declaring your class fields as protected.
If not so, then generally the better approach is to perform the same
using a public/protected member method in the parent class updating
those private fields in the parent class and then, calling that
public/protected member method from your child class' object.
This way you can achieve the implementation by calling parent's class member method from the child class' object to update those parent class' private fields.
Protected keyword for declaring the variables is used to make those instance variables visible for all the other classes in the same package and also the class[sub class] which will extends the super class involving those protected variables.
of course,you can declare the variables with private or protected modifiers.But when you declare the variable as private then you can able to hide variable such that other classes are not able to access it directly and on the other hand if you declare the variable with the protected then you are making the variable to access it directly without using any getter methods,which is against to OOP principle.
So from my opinion, Since Car is the super class of all the other class like ToyotaCar and so on.Declare the variables in your super class as private and in sub class make use of getter and setters methods to read and write depending upon your need. By doing that you are adhere to OOP principles.
Hope this helps.
Thanks

Public members in package private class

I wonder if it's okay (not considered bad practice) to have public members in package private class. I tend to add public keyword to members of my default visibility classes to indicate that such members are part of the classes API.
I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (i.e. package visibility). Is that correct?
Example:
class ModuleImplementationClass {
private int fieldA;
private String fieldB;
private void someClassInternalMethod() {
// impl
}
public int doSth() {
// method that will be called by other classes in the package
}
}
I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (i.e. package visibility). Is that correct?
Well that depends. Not if you're overriding existing methods (e.g. toString()) or implementing an interface.
If you don't want the method to be used from outside the package, make it package private. If you're happy for it to be used from anywhere, make it public. Or another way to think about it: design your method access so that if someone changed just the class access to make it a public class, you wouldn't want to change the method access too.

In Java, what happens when you have a method with an unspecified visibility keyword?

I have been working with android for a few years now, not once have I had a teacher or anyone to tell me what to do.
This whole time I have wondered to myself this.
When you have a method I generally see...
public void method(){
//Stuff
}
or
private void method(){
//stuff
}
I know that a void is a method with no return value, and that public is the visibility of the method in a way but would it matter if I just used something like this...
void method(){
//stuff
}
Because then the methods visibility would just be default anyway?
I have no idea if I am right or not, is it just good practice to specify "public" or "private" ?
Not specifying anything has a specific meaning:
public - any class can access this member
protected - subclasses can access this member (as well as code in the same class or in the same package)
private - only code in the same class can access this member
nothing ("default" access) - only code in the same package can access this member
Arguably the last case should have had its own keyword, but we're stuck with it now. Unless you really mean to use default visibility, it's poor form to not specify anything - did you really need package visibility for some reason, or did you just default to package visibility for everything? Best practice is to explicitly use private for non-public members unless you need one of the others.
Java has four levels of visibility: public, protected, (default), private
Visible to the package. the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Default Access Modifier - No keyword:
Default access modifier means we do not explicitly declare an access
modifier for a class, field, method etc.
A variable or method declared without any access control modifier is
available to any other class in the same package. The default modifier
cannot be used for methods, fields in an interface.
Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only
be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class
and interfaces cannot be private.
Variables that are declared private can be accessed outside the class
if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates
itself and hide data from the outside world.
Public Access Modifier - public:
A class, method, constructor, interface etc declared public can be
accessed from any other class. Therefore fields, methods, blocks
declared inside a public class can be accessed from any class
belonging to the Java Universe.
However if the public class we are trying to access is in a different
package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a
class are inherited by its subclasses.
Protected Access Modifier - protected:
Variables, methods and constructors which are declared protected in a
superclass can be accessed only by the subclasses in other package or
any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however methods
and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method
or variable, while preventing a nonrelated class from trying to use
it.
Java has four levels of visibility: public, protected, (default), private. The meaning of these is as follows:
public - makes your methods accessible to any other class.
protected - makes your methods accessible to any class in the same package OR any subclass of your class.
(default, i.e. no modifier) - makes your methods accessible only to classes in the same package.
private - makes your methods accessible only to the current class.
The same rules apply when specifying the access modifiers on classes, methods and fields.

Categories