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.
Related
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.
In Java, is there a way to have an access modifier which is essentially private, except that this method can be accessed by children? I am developing a program in which there are several methods which are needed by the children of a certain class (and want to avoid duplication), but I don't want to make it public as I do not want the objects these childish classes are instantiated in to have access to these methods.
If there is no such thing, what would you guys recommend as to achieving best practice on this issue?
Preferably in the same package - protected doesn't fulfil this.
This is what the protected keyword is for.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
Edit: Please be also aware that the Java Reflection API allows any class to access any member of your classes whatever the modifier.
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.
class Orange{
Orange(){
}
}
What is the difference between the usage of the modifier - in this case, package-private - in front of the class and in front of the constructor? I think the modifier in front of the constructor means it is allowed to instantiate an instance of the class Orange. But what about the modifier in front of the class?
To start with there are 4 access levels created by 3 access modifiers.
public - accessible everywhere
protected - accessible in the same package and in the children
default - accessible only in the same package
private - accessible only in the same class.
You are correct about - Modifiers at the level of constructors are directly related to the instantiation of the class.
Modifiers at the level of Class decide the accessibility of the Class.
First, to assuage any fears, the code you've provided is perfectly valid Java syntax.
In effect, you've created a class that can only be instantiated/used by other classes in the default package. It would also work if you defined it in a package (e.g. package foo;) since only the classes in package foo could see this class).
Now, to the crux of the question.
There are different ways to control access to fields and members. and they each do different things.
private visibility is the least visible. Only the defining class can access the field.
No modifier, or package private is the second least visible. The defining class and all classes within the package may access the field, but subclasses and the rest of the world cannot.
protected is the second most visible. Only other classes are prohibited from accessing the field.
public is the most visible. Everything can access the field.
Modifiers at the level of the class get interesting. This comes from the Java Language Specification, §8.1.1:
The access modifier public (§6.6) pertains only to top level classes
(§7.6) and to member classes (§8.5), not to local classes (§14.3) or
anonymous classes (§15.9.5).
The access modifiers protected and private (§6.6) pertain only to
member classes within a directly enclosing class or enum declaration
(§8.5).
The modifier static pertains only to member classes (§8.5.1), not to
top level or local or anonymous classes.
It is a compile-time error if the same modifier appears more than once
in a class declaration.
If two or more (distinct) class modifiers appear in a class
declaration, then it is customary, though not required, that they
appear in the order consistent with that shown above in the production
for ClassModifier.
In general, a class declaration appears something like this:
ClassDeclaration:
NormalClassDeclaration
EnumDeclaration
NormalClassDeclaration:
ClassModifiers(opt) class Identifier TypeParameters(opt)
Super(opt) Interfaces(opt) ClassBody
Anything with (opt) is considered optional.
So, what does this pare down to?
The JLS mandates that a class does not need a [class] modifier.
The JLS mandates that, if a [class] modifier is present, then it follows one of these rules:
If the modifier is public, then it is only applicable to top level classes and member classes.
If the modifier is protected or private, then it is only applicable to member classes within a directly enclosing class or enumeration.
The static modifier may appear, but is only applicable to member classes.
Constructors have a similar rule set.
ConstructorDeclaration:
ConstructorModifiers(opt) ConstructorDeclarator
Throws(opt) ConstructorBody
ConstructorDeclarator:
TypeParameters(opt) SimpleTypeName ( FormalParameterList(opt) )
Again, this breaks down to:
The JLS mandates that a constructor does not need a [constructor] modifier.
The JLS mandates that a constructor modifier cannot contain abstract, static, final, native, strictfp, or synchronized.
The JLS mandates, if no access modifier is specified for the constructor of a normal class, the constructor has default access (§8.8.3, emphasis mine).
You can only declare a public or default class (in case of top level classes only) in Java and these modifiers decide the accessiblity of the class.
I also suggest you to see "Why can't a class or an interface receive private or protected access modifiers?"
Now as for as constructor concerns, a constructor will have aaccess-control of type default when no access-modifier is defined explicitly. So this constructor will have a Package Level Access. Only those class which are defined within that package as that of the class with this default constructor will be able to access it. See "Aren't Java constructors public by default?"
If the constructor is made private, then only the code within that class can access this.
For a better understanding of modifiers, you need to see "Access Modifiers In Java"
Modifier of class defines who can access the class. For example public class can be accessed by classes from any package, if no modifier is written the class can be accessed by classes from the same package only.
Modifier of constructor, method and field has the same meaning. However private and protected have more sense. Private can be accessed from the current class only. Protected from its subclasses as far as from just classes from the same package.
Concerning to your question about constructor. Class can have several constructors. Some of them can be private, some other public. You are right that there is no sense to make constructor public if class is package protected: no-one outside package can call this class anyway.
This is exactly like writing public constructors for abstract classes. Since abstract class cannot be instantiated itself its constructors should be protected or private although compiler does not care about this.
BTW using default package is not commonly used and not recommended technique.
The use and types of class level modifiers:
http://javapapers.com/core-java/access-modifiers-in-java-explain/
The use and types of constructor level modifiers:
http://www.careercup.com/question?id=296844#commentThread302715
Class modifiers work similarly to method modifiers. Public, private, final, abstract, etc. work.
Public allows the class and its methods to be accessed by classes from any package.
No modifier only allows classes to be access from it's defined package.
Private would prevent all access (no point to this if using with a top-level class).
Abstract classes allow you to create child classes derived from the parent (abstract) class. For example, you can make an Abstract Shape class and have a Rectangle class extend shape, inheriting all its methods, variables, and forcing it to define any abstract methods.
Access Modifiers:
Public - {Can access anywhere in the project}
Private - {Can access only inside the class}
Protected - {Can access within the package and sub classes}
Default - {can access within the package}
Non-Access Modifiers:
Static - {for creating class variable and method}
Final - {for creating finalized variable and method}
Abstract - {for creating abstract method and class}
Synchronized - {for threads}
Some brief discussion on the above modifiers in this link. Refer it for the better understanding.
I find the best visibility level in Java to be the default visibility i.e. package visibility, because it enables unit test classes to access all the methods, if the test is placed in the same package as the main class.
Also package visibility is shorter to write since you can omit the visibility declaration, so there is less boiler plate.
The second best visibility level is protected, since in some cases you can create your test classes as sub-classes of your main class. However, as stated before, package visibility works better in most cases, if you use packages properly.
Third, typically if you run Sonar and do code review and static analysis on large projects, I have found out that typically 80% of the methods are public, and 20% are private/protected. Thus, the main idea of using private or protected methods is to protect the data/properties from being accessed by bypassing the accessors. Most of the methods will be typically public anyways.
The most useless visibility level (but unfortunately commonly used) is private as it's impossible to test (without using Reflection and modifying the visibility to something else). Also, private prohibits code re-use in sub-classes, which is the main idea of using object oriented paradigm in the first place, and thus should be avoided. For the same reasons keyword final should be avoided in most cases.
Thus, I find your example to be the best practice how to define the visibility levels, except that your constructor is not public :). However, you are missing the package declaration and unit tests.
If I have a java class which is package-private (declared with "class", not "public class"), there is really no difference if the methods inside are declared public or protected or package-private, right? So which should I use, or when should I use which? I'm a bit confused.
If I have a java class which is package-private (declared with "class", not "public class"), there is really no difference if the methods inside are declared public or protected or package-private, right?
Well maybe not immediately. But if you then (or in the future) declare a 'protected' or 'public' class that inherits from the package-private class, then the visibility of the members of the original class do matter.
As #kmccoy points out, declaring the class as final removes the possibility of subclasses.
But this is really only window-dressing. If you then decide that you really need to create subclasses, you simply remove the final ... and then you are back in the situation where the choice of access modifiers does matter.
IMO, the bottom line is that you should pick the most appropriate modifiers ... even if it is not necessary right now. If nothing else, your choice of modifiers should document your intent as to where the abstraction boundaries lie.
Public methods inside a package class are public to classes in the same package. But, private methods will not be accessible by classes in the same package.