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
Related
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.
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.
Before nothing,
my problem is simmilar to these:
get super class value in java
Getting the name of a sub-class from within a super-class
but not solve my problem. So, I'm going to explain it. I expect no repeat a topic...
I'm creating a hierarchy. This hierarchy is only for Object with getter and setter. Just for show information.
Well, I want to do correctly my hierarchy but without do something ilogical with modifiers. This is a simplified example of my Classes, is not exactly Java is pseudocode:
Class A
private id;
Class B extends A
private dataB;
Class C extends A
private dataC;
Variable "id" is common for Class B and Class C. Because that B and C extends A.
I'm thinking that never I going to use Class A for show data, just B and C, like if A were an Abstract Class.
My problem is:
I don't know if is correct put methods getter and setter in class A with modifiers public and use this methods from Classes B and C, because the hierarchy is correct, is logical but the data "id" is not correctly encapsulated.
Class A
private id;
private name;
private age;
public getId(){...}
public getName(){...}
public getAge(){...}
Class B extends A
private dataB;
public getDataB(){...}
Class C extends A
private dataC;
public getDataC(){...}
To access to my object I want to do this:
B.getDataB();
B.getId();
B.getName();
B.getAge();
C.getDataC();
C.getId();
C.getName();
C.getAge();
This works but all method of Class A must be public, the variables aren't correctly encapsulated.
Are there other ways to do this?
Is this the best/worst way?
Getters and setters could be an exception to "jump" the logical of the modifiers?
I excpect you could understand my example and my "English".
Thank you in advanced.
There are various ways of achieving encapsulation.
The best way is to make public methods in base class to access private data member. That is what you have applied.
The other way is to make your base class members protected and public methods in subclass (that inherits them) to get and set them.
As per my knowledge and other JAVA books authors like Paul Deitel prefers the first method to achieve maximum encapsulation.
About getter/setter there is very simple rule :
If you declare variable in class A getter/setter should be provide in class A. If you need any mutation in child class then override.
This make code more readable and easy to debug.
BTW you can't write getter/setter of id anywhere other then class A because it's private. SO, also in this case the above theory complies.
In simple,
You can declare variable as private. But related getter/setter must be public.
Hope it will help you.
Actually We use getters and setters for
Reusability
to perform validation in later stages of programming
Getter and setter methods are public interfaces to access private
class members.
Encapsulation Procedure:
The encapsulation procedure is to make fields private and methods public.
Getter Methods: We can get access to private variables.
Setter Methods: We can modify private fields.
Even though the getter and setter methods do not add new functionality, we can change our mind come back later to make that method safer and faster.
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
I have an abstract java class that implements a couple of its methods, but not others. In the methods it implements it uses a private attribute variable. The variable used also needs to be used in a subclass.
As I see it my options are:
Declare the private variable in both the subclass and the super class
defer the implementation of the methods currently implemented in the abstract class to the subclasses
Are there other options? Which of these makes more sense and why?
The question is how you want to maintain your state: If it is of no concern, where the value is stored, you can just add a private member "on top" of the other and use that instead of the one in the superclass. If you want to have some methods from your superclass and some methods from your subclass to access the same state, you need to change visibility:
You could declare the variable as protected, making it accessible in the subclass, or implement accessor methods, or even make it public.
Hopefully the abstract class has been designed such that you shouldn't need access to the private fields. As to which of your two methods to use, that depends entirely on what the abstract class and your subclass are and what they're supposed to be doing.
If you only need read access to this variable and the superclass methods don't modify it, you can just add another (completely separate) private field of the same name/type to your subclass. If you're attempting to modify the behaviour of the superclass methods by changing the field, you're going to have to override the methods instead.