Private and public java access modifier basics - java

I am relatively new to java and I did some reading about private and public acccess modifiers. I would like to eliminate any confusion once and forall in this topic because I feel like I don't have the best grasp on it.
Access modifiers in variables
Please correct me if I am wrong, a variable is public on default. If the access modifier is set to public or just not set at all, than other classes from the same project can access the integer and/or modify it. If it is private than it is not visible to the outside and cannot be accessed by classes outside the one in which it was created.
Accesss modifiers in classes
Access modifiers in classes, I don't seem to fully understand. As far as my understanding, if I call a private method from method that is not in the same class, than it will not work. If it is public than it will?
Is there anything I am missing or don't understand correctly?
I appreciate help in this regard.

Please correct me if I am wrong, a variable is public on default.
You're wrong. Assuming you mean fields, by default, they have "package" access, which can't be expressed explicitly. Local variables have no concept of access control - they only exist within the context of a method anyway, so can't be referred to from anywhere else.
If the access modifier is set to public or just not set at all, than other classes from the same project can access the integer and/or modify it.
If it's set public, then any code can access it.
If it's default (package) access, then any code in the same package can access it.
Access modifiers in classes, I don't seem to fully understand. As far as my understanding, if I call a private method from method that is not in the same class, than it will not work. If it is public than it will?
That's pretty much right, yes.
I suggest you read the Java tutorial on all of this, and consult the language spec section 6.6 for more details.

Here's a good doc on the subject.
There are four access levels:
private: Only that class (not even descendants) can access.
protected: Only that class and its descendants and classes in the same package can access.
package-private (no specifier)--only classes in the same package can access--even subclasses that are not in the same package cannot.
public: Everything can access.
For for both classes member variables and methods, the default access is package private.

You can find information about the 4 modifiers here on Oracles website.
If you do not specify the modifier, it is said to be on default, which means only any code in the same package can access it.
If it's set public, then any code in any package can access it.

Actually in Java there are four different access modifiers, private, public, protected and package specific. "Please correct me if I am wrong, a variable is public on default" - you are wrong here a variable if not declared differently has a package related access. If it is set to public then it can be modified by other classes even outside of the original package. This website - http://javapapers.com/core-java/access-modifiers-in-java-explain/ - can provide you useful hints. Actually it is very easy once you read a bit more on OO concepts such as Encapsulation. Then you will understand the purpose of access modifiers (to ensure data integerity).

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
Default : Visible to the package. No modifiers are needed.
Private : Visible to the class only.
Public : Visible to the world. All classes and packages.
Protected : Visible to the package and all subclasses.
If no access modifier is specified by the programmer, default access modifier is used.

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 class, variable and method}
Abstract - {for creating abstract method and class}
Synchronized - {for threads}
To learn more follow this link

private and public java access specifiers.in java,private access specifiers it specifies the access.private is like own family property that can uses only which family belongs.that means inside the class,method and variable can be used.
public is like government properties that means every one can access the properties without any need of tokens

private and public java access specifiers.in java,private access specifiers it specifies the access.
private is like own family property that can uses only which family
belongs.that means inside the class,method and variable can be used
.
public is like government properties that means every one can access
the properties without any need of tokens

Related

What happens when a variable is not "public" or "private"?

I see that there are two ways to declare/define a variable in JAVA: public and private. My question is what happens if the variables is defined without being treated as "public" or "private", for example:
int num;
Is 'num' considered as private of as public?
The are four ways of defining the access permisions of a variable, as described here. If you don't put a keyword before the variable name you are using the default access level modifier.
public allows access from anywhere else.
protected allows acces from inside the package and the class' subclasses.
the default modifier (blank) allows access only from inside the package.
private allows access only from inside the class.
Protected and default are quite similar.
The variable's access in then called package private. That means that it can only be accessed by classes in the same package as the class with the variable.
One use of the package private access modifier is in testing (usually not used for the variables, but for methods and/or constructors)

private access modifier and protected access modifier [duplicate]

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.

The use of visibility modifiers in Java

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.

Protecting internal class variable in jar

We have a getter method within a class.
Within the same JAR we want the variable to be accessible with the no-identifier access level, from the same package and subpackages.
Below the access levels from: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Our problem is, how do we stop someone from taking the compiled .JAR, creating a class with the same package namespace definition, and being able to access our variable through the getter?
We thought about getting rid of all getters for the specific variable, and giving the variable value to other classes with setters and constructors, when they pass a reference to themselves. Obviously, they will be final classes. This way all objects needing the variable value have their own private copy.
I'm wondering though if there is a better way?
Access control modifiers (public, private, protected) are not meant as a security tool, but as an OO design tool. They're used to implement OO patterns like encapsulation, inheritance.
Even with no getter whatsoever and a private variable, any Java developer can use reflection to access the variable.
If you want to keep something secret, don't ever put it in a variable of a program executed by anyone. Keep it on your own machines.
- Reflection seems to be the evil here, using which any variable even with private access modifier can be accessed.
- Four access controls like private, default, protected, and public are introduced in Java more as a tool to support the Core Object Oriented Concept like Inheritance, Encapsulation etc...

What is the default access specifier in Java?

I just started reading a Java book and wondered; which access specifier is the default one, if none is specified?
The default visibility is known as “package-private” (though you can't use this explicitly), which means the field will be accessible from inside the same package to which the class belongs.
As mdma pointed out, it isn't true for interface members though, for which the default is "public".
See Java's Access Specifiers
The default specifier depends upon context.
For classes, and interface declarations, the default is package private. This falls between protected and private, allowing only classes in the same package access. (protected is like this, but also allowing access to subclasses outside of the package.)
class MyClass // package private
{
int field; // package private field
void calc() { // package private method
}
}
For interface members (fields and methods), the default access is public. But note that the interface declaration itself defaults to package private.
interface MyInterface // package private
{
int field1; // static final public
void method1(); // public abstract
}
If we then have the declaration
public interface MyInterface2 extends MyInterface
{
}
Classes using MyInterface2 can then see field1 and method1 from the super interface, because they are public, even though they cannot see the declaration of MyInterface itself.
If no access specifier is given, it's package-level access (there is no explicit specifier for this) for classes and class members. Interface methods are implicitly public.
The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.
Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package
It depends on what the thing is.
Top-level types (that is, classes, enums, interfaces, and annotation types not declared inside another type) are package-private by default. (JLS §6.6.1)
In classes, all members (that means fields, methods, and nested type declarations) and constructors are package-private by default. (JLS §6.6.1)
When a class has no explicitly declared constructor, the compiler inserts a default zero-argument constructor which has the same access specifier as the class. (JLS §8.8.9) The default constructor is commonly misstated as always being public, but in rare cases that's not equivalent.
In enums, constructors are private by default. Indeed, enum contructors must be private, and it is an error to specify them as public or protected. Enum constants are always public, and do not permit any access specifier. Other members of enums are package-private by default. (JLS §8.9)
In interfaces and annotation types, all members (again, that means fields, methods, and nested type declarations) are public by default. Indeed, members of interfaces and annotation types must be public, and it is an error to specify them as private or protected. (JLS §9.3 to 9.5)
Local classes are named classes declared inside a method, constructor, or initializer block. They are scoped to the {..} block in which they are declared and do not permit any access specifier. (JLS §14.3) Using reflection, you can instantiate local classes from elsewhere, and they are package-private, although I'm not sure if that detail is in the JLS.
Anonymous classes are custom classes created with new which specify a class body directly in the expression. (JLS §15.9.5) Their syntax does not permit any access specifier. Using reflection, you can instantiate anonymous classes from elsewhere, and both they and their generated constructors are are package-private, although I'm not sure if that detail is in the JLS.
Instance and static initializer blocks do not have access specifiers at the language level (JLS §8.6 & 8.7), but static initializer blocks are implemented as a method named <clinit> (JVMS §2.9), so the method must, internally, have some access specifier. I examined classes compiled by javac and by Eclipse's compiler using a hex editor and found that both generate the method as package-private. However, you can't call <clinit>() within the language because the < and > characters are invalid in a method name, and the reflection methods are hardwired to deny its existence, so effectively its access specifier is no access. The method can only be called by the VM, during class initialization. Instance initializer blocks are not compiled as separate methods; their code is copied into each constructor, so they can't be accessed individually, even by reflection.
default is a keyword that is used as an access modifier for methods and variables.
Using this access modifier will make your class, variable, method or constructor acessible from own class or package, it will be also is set if no access modifier is present.
Access Levels
Modifier Class Package Subclass EveryWhere
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N
if you use a default in a interface you will be able to implement a method there like this exemple
public interface Computer {
default void Start() {
throw new UnsupportedOperationException("Error");
}
}
However it will only works from the 8 Java version
Official Documentation
Access Modifiers in Java
See here for more details. The default is none of private/public/protected, but a completely different access specification. It's not widely used, and I prefer to be much more specific in my access definitions.
the default access specifier is package.Classes can access the members of other classes in the same package.but outside the package it appears as private
Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:
Bill Venners: Java has four access levels. The default is package. I
have always wondered if making package access default was convenient
because the three keywords that people from C++ already knew about
were private, protected, and public. Or if you had some particular
reason that you felt package access should be the default.
James Gosling: A package is generally a set of things that are kind of
written together. So generically I could have done one of two things.
One was force you always to put in a keyword that gives you the
domain. Or I could have had a default value. And then the question is,
what makes a sensible default? And I tend to go for what is the least
dangerous thing.
So public would have been a really bad thing to make the default.
Private would probably have been a bad thing to make a default, if
only because people actually don't write private methods that often.
And same thing with protected. And in looking at a bunch of code that
I had, I decided that the most common thing that was reasonably safe
was in the package. And C++ didn't have a keyword for that, because
they didn't have a notion of packages.
But I liked it rather than the friends notion, because with friends
you kind of have to enumerate who all of your friends are, and so if
you add a new class to a package, then you generally end up having to
go to all of the classes in that package and update their friends,
which I had always found to be a complete pain in the butt.
But the friends list itself causes sort of a versioning problem. And
so there was this notion of a friendly class. And the nice thing that
I was making that the default -- I'll solve the problem so what should
the keyword be?
For a while there actually was a friendly keyword. But because all the
others start with "P," it was "phriendly" with a "PH." But that was
only in there for maybe a day.
http://www.artima.com/intv/gosling2P.html
Update Java 8 usage of default keyword:
As many others have noted The default visibility (no keyword)
the field will be accessible from inside the same package to which the
class belongs.
Not to be confused with the new Java 8 feature (Default Methods) that allows an interface to provide an implementation when its labeled with the default keyword.
See: Access modifiers
There is an access modifier called "default" in JAVA, which allows direct instance creation of that entity only within that package.
Here is a useful link:
Java Access Modifiers/Specifiers
First of all let me say one thing there is no such term as "Access specifier" in java. We should call everything as "Modifiers". As we know that final, static, synchronised, volatile.... are called as modifiers, even Public, private, protected, default, abstract should also be called as modifiers . Default is such a modifiers where physical existence is not there but no modifiers is placed then it should be treated as default modifiers.
To justify this take one example:
public class Simple{  
    public static void main(String args[]){  
     System.out.println("Hello Java");  
    }  
}  
Output will be: Hello Java
Now change public to private and see what compiler error you get:
It says "Modifier private is not allowed here"
What conclusion is someone can be wrong or some tutorial can be wrong but compiler cannot be wrong.
So we can say there is no term access specifier in java everything is modifiers.

Categories