This question already has answers here:
Why Java allows increasing the visibility of protected methods in child class?
(4 answers)
Closed 5 years ago.
When I try to access and override an inherited abstract function from an abstract class which is of protected access level,
protected <ReturnDataType> <FunctionName>() {
upon removing the Access Type Protected, Eclipse throws me this error
Cannot reduce the visibility of the inherited method from the < inherited class >
which is resolved with the quickfix of giving it the accesstype Protected.
I know that, I can also have the access type as Public for this overrided function.
Now, my question is:: What is the risk / issue with me having this function as Public?
It is a means to help protect your code against errors. There exists coding languages without encapsulation. At their most extreme, any code can change any piece of any data and we may simply not want that to be possible. A disciplined coder will reduce the number of places a given type of data is manipulated, but it may still not be obvious all the combinations of operations that could leave objects* in different states. The situation gets worse when their code is then used as part of someone else's code. So the risks of changing these accessTypes is that it can cause errors down the line if used improperly.
All public does is allow the variable to be accessed through another package, so if someone imported your project as a external library into their project they would be able to access a global variable. This page may be of some use to you: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Related
This question already has answers here:
class or method alias in java
(8 answers)
Closed 3 years ago.
I have a class with a probably unnecessarily cumbersome name, that contains a lot of static methods I use elsewhere.
Rather than fill my code with a lot of
VeryUnnecessarilyLongCumbersomeName.doThingFoo();
VeryUnnecessarilyLongCumbersomeName.doThingBar();
VeryUnnecessarilyLongCumbersomeName.doThingEgg();
VeryUnnecessarilyLongCumbersomeName.doThingSpam();
I would rather have
VeryUnnecessarilyLongCumbersomeName thing = new VeryUnnecessarilyLongCumbersomeName();
thing.doThingFoo();
thing.doThingBar();
thing.doThingEgg();
thing.doThingSpam();
However, this gets the warning
"the static method doThingFoo() should be accessed in a static way."
I know there are multiple solutions here. Use better class names. Make it not static. Ignore it because it's just a warning.
But I don't actually think it should be a warning. What harm does doing it this way cause? Is there a more elegant/correct way to make my code less clunky that isn't one of the above solutions?
NOTE: I suspect this might warrant the coding-style tag and therefore be considered off-topic and get rejected. I was thinking there's room here for a question like this, however, so I leave it up to y'all.
Although it is not technically harmful because it technically works, the problem with this is it is misleading, and any values that the instance thing contains, do not actually matter at all for the results of the methods.
Typical Java Convention:
When accessing a method through an instance, one would expect the result to be dependent on the values of the instance.
When accessing a method through a Class name, one would expect the result to be independent of the values of any instance.
Your way:
You are accessing a method through an instance and expecting it to be independent of any instance.
So why use an instance for an instance independent method? That is why it is misleading. I would suggest attempting to shorten the class name rather than accessing static methods through an instance.
How about changing the VeryUnnecessarilyLongCumbersomeName class?
Static methods are there to be used without instances. They are meant to be used if you want to invoke the method without first initializing a class. The downside of using static methods is that you lose all kinds of OOP benefits; You lose virtual dispatch and subsequently polymorphism. You can never override that method in a derived class. Of course you can declare a new (static) method in a derived class, but any code that accesses it has to be aware of the entire class hierarchy and do explicit checking and casting, which is precisely what OO is supposed to avoid.
Also, it is confusing. When another programmer sees your code, he/she will think upon seeing a static he/she will assume that it will not require a valid instance to invoke the method.
TLDR; don't do it and stick with the best practices =)
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
I know it has been asked before, but I still am not truly getting it.
People say it is about encapsulation, to protect the fields from outside classes from being accessed? But what's the point of protecting the fields if you are using a get/set methods to change and access the fields anyways?
People also said using get/set methods, you can have the flexibility to add more logic into the methods. I agree, but what happens if your program will never require such a thing? In that case, can you just still declare the field as public instead of get/set method?
You should not set your field as public. This is encapsulation in java. Others doesn't know how the values are populated in to the private variables, they may change it from several places, atlast it become a huge mess. But they have access to some method which is public. I didn't say Getters/Setters.
So up to your point Getter/Setter . Don't use that if you follow java encapsulation. This is same as public variable then (May be some more logic added to it, but user can alter that using setter).
What you have to do is, expose public method in the same class, do whatever manipulation you want to do with instance variables and return only the required results that user need to know.
Eg: Take a class CocaCola . You write a method createCola(). inside that you create the cola and return the result. User doesn't need to know the ingredients of Cola. If you create Getter/Setter otr make the ingredient public that is worse.
These are just standards or best approach in java, that experts suggest. So if you don't want to follow, you don't need to .
Refer:
Java Getters/Setters are evil
It is my understanding that if you make your fields public, other programs running on the same machine can access and edit the data unchecked (Someone correct me if I am wrong). Then there is the possibility of the program trying to store a String object into an address that is supposed to point to an Integer, resulting in an exception that could potentially be a security flaw.
The main idea is that if someone else uses your class as part of a bigger program, the set method can include validity checking and exception handling so as to protect them from having to deal with it.
Example:
private int value;
public void setNonNegativeValue(int newValue){
try{
if (newValue >= 0){
value = newValue;
}
} catch (Exception e){
//handle it here
}
}
Now obviously this method isn't going to result in needing Exception handling, but you see how more complicated ones could.
In this case, value can only be a positive number because the setter method checks for that. However, if value was public, any class could just do myClass.value = -1; This would be a problem if you needed value to be positive
public fields mean every one can access and modify them , but having private fields does not mean you have to declare its setter/getter every time it may depend upon your requirement, for suppose there is such field you want user to get its value but not to change its value. this is all data hiding depending upon your business.
This question already has answers here:
Why are getter and setter method important in java? [duplicate]
(6 answers)
Closed 8 years ago.
If I create a class in Java, I've always been taught that the convention is to make all fields of a class private. If I need to access or change them, I can create an accessor and mutator method. I do understand the importance of private variables, as they help reduce complexity and allow for encapsulation.
What I don't understand is that if I create a public accesor and mutator method, isn't the variable public at that point? Why is it still convention to use private variables in situations where anyone can access them?
I should also note that I understand the important of these methods, but I would like to know why we bother to make the variable private even though we are giving anyone access to it through those methods?
Yes, you're right, it does effectively make the variable public. But there's one important difference, which is that it gives you the ability to change things later on: you can remove the setter if you want, or make it private, without affecting code that reads from the field using the getter.
If you'd just made the variable public, you wouldn't be able to stop writes to the field without also breaking reads from the field.
It has other advantages. You can make the access synchronized if you want to later on, without breaking client code, for instance. In short, it allows lots of modifications later on that wouldn't otherwise be possible without causing lots of breakages in code that uses the class.
And you can add extra logic that logs whenever someone writes to the field, or prevents certain threads from writing, or whatever... you can change the type of a field from a HashMap to a TreeMap if your getter abstracts it away and just returns a Map... etc.
Private fields are considered to be internal to the object. So the outside world doesn't need to know about how the data is stored inside the object. This means you can easily change the internal representation of data of an object while everyone else still uses the same accessors / mutators to do its work.
It's also possible that accessors / mutators perform validation and other steps that are needed internally for the object but that you don't wish to expose to code that uses the object.
You could make all fields public but that limits your ability to change the internal structure of the object later on when a lot of code now depends on a field being named a certain way.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What’s “#Override” there for in java?
Since Java 1.5 this annotation was incorporated to the language to be used on methods that overwrite a superclass methods.
Now, what changes in a method that uses this annotation to one that doesn't use it? Is this just convention?
Assuming, obviously, that both be methods that overwrite a method from its superclass...
#Override creates a compile-time check that a method is being overridden.
This is very useful to make sure you do not have a silly signature issue when trying to override
It not only makes the compiler check but also documents the
developer's intention.
if you override a method but don't use it anywhere from the type itself, someone coming to the code later may know the purpose. The annotation explains its purpose.
A good IDE will helpfully flag any method that overrides a method without #Override, so the combination of the two will help ensure that you're doing what you're trying to.
it also improves readability
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Private vs. Public members in practice (how important is encapsulation?)
Recently I've been coming across a situation where I declare a class variable as public, because it will be used in another class. Someone told me recently that I should make such variables private and write a public method returning the value of the variable. I was told this was good practice. I searched through my Java book and couldnt find any reference to this. My question is, is it good practice to declare as many as possible class variables as private?
Yes. Generally, all variables should be private (not protected, private), and there should be methods to get their values (and possibly set them) if (and only if) you want to allow that by outsiders. The variables you use are an implementation detail, and usually contain data that has to be a certain way. Getters and setters allow you to take responsibility for that data, validate it, synchronize it, etc, instead of letting some jackass store random stuff in it and potentially make your object unusable.
The sole exception might be classes whose only purpose is storage of data so you can ship it around as one object, kinda like a C/C++ struct. But then, you're making a decision that no, you don't want to validate, synchonize, encapsulate that data in any way...and changing your mind later breaks binary compatibility (meaning any code that touched that class will need to be recompiled). Not a big deal in a little private project; huge deal in a public framework/API.