This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 7 years ago.
I am learning Java and there's something bothering me and the textbook doesn't explain it.
I understand that you use modifiers to declare methods inside classes and all. But I suddenly got to a class declared like
static void(){
}
Why is there no public or private modifier and it still works? Can I avoid using the public modifier everywhere else or how does that work? I understand that static means member of the class and void that it doesn't return a value. Yet why not public or private for that matter.
For the sake of this explanation, the terms "functions" and "methods" are used interchangably. There is a small difference between them, for more information, ask Google.
Methods in Java that do not explicitly specify a modifier are by default package-private, so the method is visible to all the classes in the same package as the class where the method is declared.
Public functions are callable by all classes that have access to the class (i.e your whole project) and private methods are only callable within the class the method was written in. There is also the protected modifier, which specifies that the functions can only be accessed by the class, all its subclasses and classes in the same package.
"Why is that important?", you may ask. Good question!
You should use modifiers to hide methods/properties from other classes which may (ab)use them or in a bad case could lead to unexpected behaviour (not necessarily technically, but semantically... some methods just need a little more privacy just like we do). So a good place to start is private, which means only the class it is declared in is able to call it. More often than not, you'll need to give other classes access to methods, which is why the package-private, protected and public modifiers exist.
Data encapsulation is an important paradigm in programming, and these modifiers help you achieve just that.
Related
This question already has answers here:
Is it possible to hide or lower access to Inherited Methods in Java?
(8 answers)
Closed 5 years ago.
I am writing a program where there are quite a lot number of methods in a particular class, so I decided to write an abstract class to help in keeping track of the methods.
Now, consider this: I have declared a method as abstract in the abstract class, and in the other class (which extends the abstract class), I want to override this method, but with access privilege reduced to private. Here, the compiler is giving a problem. It says that an attempt to assign weaker access privileges is being met with, which cannot be allowed. If I try to declare the method in the abstract class as protected (I have also changed the private ones to protected in the sub-class), it says that modifiers abstract and protected cannot be used together.
So, what can I do? Do I have to make the methods package access or public in both classes? If so, is there no way that I can declare these methods private?
Please note that I'm asking only for abstract classes, and not all classes in general.
What do you mean it can not be protected abstract - of course it can.
And the thing that you want to do is basically prohibited by the compiler and the language itself in the first place.
The answer to your question is: there's nothing you can do to reduce the visibility of a method declared in a parent class.
If you can restate what you're trying to accomplish by "keeping track of the methods" in an abstract parent class, you might get a different solution.
This question already has answers here:
how to restrict protected method access to only subclasses
(2 answers)
Closed 5 years ago.
I have a question I hope you can help me with:
I have an abstract class that contains some utility abstract methods, but I want these methods to be restricted only to subclasses, I obviously can't use a private modifier, but protected is not enough because in the same package there are also classes that don't extend it, but they can use these methods if the extended ones are instantiated in them:
What can I do?
Thanks!
You can't do it. The only way is to rearrange your package structure in a way, that only the base class and its children were inside the package. To achive this, you may move all the classes that aren't children into a subpackage - they won't see protected methods.
Out of curiosity - why do you need this? The only reason that comes to my mind is to prevent programmers error, because malicious code may access these methods using reflection anyway.
This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 8 years ago.
I have a problem understanding access modifiers in Java.
public: can be used anywhere.
private: can only be used inside the same class.
protected: can only be used in subclasses.
I saw many examples and tried but I couldn't understand.
I know only the definition. Please any one help me one this give me more examples.
What kind of programs would use private?
What kind of programs would use protected?
What kind of programs would use public?
This is very basic in OOP concepts. When the class should need to not to expose it parameters, it would define them as "private". Any class outside have no any access to it. Either these variables are for the use of the class itself only or there are public getters and setters which give indirect but controlled access to these variables.
example is age. Let say someone need to set minus value to age, then the setter method can avoid setting that value. It is a bad practice in OOP to expose variables as public. If you do that, any other logic which can create an instance of the class can change the value of the varible.
The variables are marked "protected" when we need to allow sub classes too can use or have access to these variables.
Mostly public access modifier is used for methods
You would use all three in all kinds of programs, except for very simple programs where everything is typically public.
A good practice is to use the most restrictive access modifier that you can. Access modifiers exist to help you stop yourself from making mistakes - they are not actually required per se, but they are very useful. If you're writing a library for other people to use (which you aren't, but you might in the future) they also stop other people doing weird things with your code.
Usually, a class is related to one thing (e.g. a book in a library). If you are writing a library system, you might have a class like this:
public class Book
{
private String title;
public String getTitle() {return title;}
public Book(String t) {title = t;}
...
}
Notice that title is private, so you can't directly get or set the title of a Book. You can indirectly get it using the getTitle method, which is public. You can only set it once, when the Book is created.
Code inside the Book class can still set the title, so this is not foolproof. final would be better for that, but this is to demonstrate access modifiers, not final.
You could just make title public, and say that you won't change the title of a book, but later you might do it by mistake. Again, access modifiers help you prevent yourself (and sometimes other people) making mistakes.
Edit: Also, you're wrong about protected. protected things are accessible to subclasses or classes in the same package. There's also a default access modifier, which has no keyword, which you get if you don't use public, protected or private. The default access modifier makes things accessible to the same package only.
private is used when you have variables or methods in a class which you will not use outside the class.
public is used for variables and methods which need to be accessed outside this class.
protected is used when the variables need to be used only that class and in its child class.
here is a good example.
This question already has answers here:
Pros and cons of package private classes in Java?
(8 answers)
Closed 9 years ago.
I love access control in any language, but I find that in Java I almost never (if ever) use the package-private access modifier (or lack thereof).
I realize that inner classes can be private, protected, or package-private, but outer classes can only be package-private or public. Why can an outer class be package-private but not protected? What is the benefit of restricting classes/methods/fields to be seen by the entire package, but not subclasses?
I use package-private classes and methods when I want to hide implementation details from users (and other classes) outside the package.
For example if I have an interface and a factory class that creates instances of that interface, I may have the implementation class as a separate file but mark it package-private so others can not use it, nor will it clutter the JavaDoc (if javadoc set to only show public).
If you seal your jar file, package-private methods can also help restrict who can access these methods. If a method is public or protected, subclasses can still see and call that method even if it's in a different package. (Unsealed jars allow anyone to make classes in your packages so they will get access to package-private or protected methods)
In many cases, peer classes in the same package have the same author, thus he knows about the inner way these classes work, or in other words he knows about the encapsulated logic of these classes. Thus he can make sure that package-private accesses between classes adhere to the encapsulated logic of the accessed class and that these accesses do not break anything.
These direct accesses are often useful for optimizations and for keeping the amount of source code smaller.
For the question part why outer classes may be package-private, but not protected, I have no answer.
I'm tidying up some of my code with the correct scope on some methods and attributes (I have two classes and at the moment I have a number which I just declared as public to get working, but I feel I should look into this and make private where possible, for better practice)
When working in eclipse it's suggested on one method, when i change it private from public, that I can fix it by dropping off the scope so the method just says "static void" instead of public/private static void.
Is this a better scenario to have nothing, rather than private or public - or is the default scope equivelant to public anyway ?
Thanks
If you leave out the visiblity modifier you default to "Package Private".
This link documents the differences between each modifier. Without knowing more about your code I can't say which one you might be best off using.
The default Java scope is "package level", i.e., every other class in the same package can access the method/field, but nothing outside the package can. It's distinct from public, protected and private.
If the class is package private (not declared with public class), then having public methods won't make them more public than having no modifier.
For interfaces, the public modifier on methods is superfluous, too (in this case, having no visibility modifier is equivalent to declaring it public). - This just for completeness, I know that you asked about static methods.