public, private and regular variable [duplicate] - java

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 just though about it:
if you have class like this:
public class a
{
int x = 5;
//setter & getter
}
you can't access to x from another class unless it is public.
so, that i know, but if it is like that, why do i need to use private?
the x variable cannot be accessed outside of the class without public or in other cases static reserved words.
so, the question(s):
what do i need the private for?
do i have to use the private or it doesn't really matter?

No access specifier is not the same as private.
When you have no access specifier, as in your example, the variable x is accessible in class a, but also in all other classes that are in the same package as class a.
When it is private, it is only accessible in class a, and not in any other class.
See Controlling Access to Members of a Class in Oracle's Java Tutorials.

By leaving out the access modifier, you are relying on the language's default.
For example, in C# class variables default to private.

The most used access modifiers are undoubtedly public and private.
public means you expose your field or method to every other class. This is useful for methods that are necessary to let the class perform its major function(s) and, in some cases, for constants that need to be visible.
private means you hide the member from every other class. This is useful for internal state and functions which other classes must not know about. This enforces the concept of information hiding.
The other modifiers protected and default (when no modifier is mentioned) are intermediate levels of access which can be useful in specific cases.
For example when sub classes need access to a method in the parent (or base) class and you don't want other classes to be able to access it, you can make it protected.
The default access modifier is more restricting than protected and can be used to allow access only from within the same package. This can be useful if a package contains a group of tightly related classes which need to interact among each other via methods which you don't want to expose elsewhere, not even to sub classes outside this package.
Maybe you will also benefit from this article.

this question is already answered in stackoverflow in this link.
There is 4 types of access restrictions in java:
public: the attribute is accessible for all clients
private: the attribute is only accessible from the class, not subclasses.
protected: the attribute is accessible from package and subclasses.
no modifier: the attribute is accessible from the class and package.
It's necessary to declare the scope of accessibility to encapsulate the functionality correctly.

Related

Logic behind behavior of the Java class protected members [duplicate]

This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 4 years ago.
Can please someone explain me the logic (not the behavior itself but the logic) behind the peculiar fact that access to protected class members, both methods and fields I believe, is allowed through inheritance only i.e. by the reference of the child type – and not by the reference of the parent type where protected member was declared – in case child class is located in a different package ?
And what if both parent and child classes are in the same package, does call by inheritance is only allowed option as well?
Also why it's not allowed to access A's protected methods for another class (B) from a different inheritance tree (C)?
access to protected class members <...> is allowed through inheritance only i.e. by the reference of the child type – and not by the reference of the parent type where protected member was declared – in case child class is located in a different package ?
This is because protected means access from children classes OR same package. From different classes you can access to members only from the same package. That's why you need to refer to members using child class reference.
what if both parent and child classes are in the same package, does call by inheritance is only allowed option as well?
If the caller in the same package -- you can use whatever reference (either parent or child)
why it's not allowed to access A's protected methods for another class (B) from a different inheritance tree (C)?
Code would be nice to see, but from my understanding of the question, that's exactly what protected modifier need to do.
When implementing something you will normally want to reduce the "attack surface" and not expose implementation details. This is why different access levels are needed. The reason for protected is inheritance. We need something which is more strict than public (to hide implementation details), but less strict than private - so that subclasses would have access.
I think this logic is best explained by JLS §6.6.2. Details on protected Access:
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
I think this should explain the logic of "class, package, subclass in same or different package":
class should be clear, the class itself should of course have access to its members.
subclass (same or different package) is also understandable.
package is not so logical, to be honest. Possible explanation: it is likely that other classes in the same package will be used in the implementation of this object.
I agree that protected is somewhat illogical. It combines restrictions on horizontal access (this package/other package) with restrictions on vertical access (subclass/not subclass).
And what if both parent and child classes are in the same package, does call by inheritance is only allowed option as well?
No. Other classes from the same package also have access to protected members of this class.
Also why it's not allowed to access A's protected methods for another class (B) from a different inheritance tree (C)?
This is specifically the intention of protected. This is done to hide implementation details of A from the "outside world".

Default access modifier for a method in interface in java? [duplicate]

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.

Protected vs Public in terms of Inheritance in Java [duplicate]

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.
When should one use Public over Protected in Java when creating Superclasses, if a program runs without any problems with a Protected access modifier set is there any need to change it to Public?
You should follow the Principle of Least Privilege.
This means that members should be assigned the minimum accessibility needed for the program to work.
If an unrelated class needs access, make it public. Typically this is done only for methods that provide managed access to data.
If the subclass is to be completely trusted in manipulating the data, and it needs it to work properly, you can make the member protected.
Else, make it private, so no other class can access it (without going through other more accessible methods that help encapsulate the data).
If your program works well when it's protected, then do not make it public. Consider making it private, with protected methods that access it, to encapsulate the data better.
Use protected in a superclass only if you want your variable or method to be accessed or overridden by a subclass of that superclass but you do not want that variable or method to be accessed outside of the superclass or subclass (i.e. publicly).
Use public when you want your variable or method to be accessed by any class. Note that you should rarely have public non-final variables or public mutable variables.
if a program runs without any problems with a Protected access
modifier set is there any need to change it to Public?
No, use the least accessible access modifiers for your variables and methods. Therefore if they are not required as public, do not make them public and only make them protected if they are required to be protected (i.e. required by subclasses). Otherwise make them private.
For the reasoning behind this, see the section "Item 13: Minimize the accessibility of classes and members" in Effective Java by Joshua Bloch: http://uet.vnu.edu.vn/~chauttm/e-books/java/Effective.Java.2nd.Edition.May.2008.3000th.Release.pdf
Recall what those access modifiers are doing.
public fields are fields that any class that uses this class can modify.
protected fields are fields that the class, its child classes, and classes in the same package can access.
There is greater risk involved in changing the visibility of those fields, depending on what it is your data is encapsulating. I would strongly recommend against those sorts of declarations.

Is a class private or public by default in Java and C++?

Are classes private or public by default in Java and C++?
Java:
By default, the classes visibility is package private, i.e. only visible for classes in the same package.
C++:
The class has no visibility defined like in Java. They are visible if you included them to the compilation unit.
In Java, a top-level class is either public or non-public. There is no "private". You can only use the public keyword or leave it off. If you leave it off it is non-public, i.e., visible only to other classes in the same package.
A nested class, that is, a class inside of another class, can be made public, package-private, protected, or private, just like any other class member. The default (i.e., the one with no modifier) is package-private, visible only to classes in the same package.
EDIT: Forgot the C++ answer, so see (and upvote) #zeller's answer. :)
According to §6.6.1 of the JLS,
If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.
So, a Java class is by default package-private.
This doesn't apply to C++, however. A class lacks visibility -- only its members can have access control. See §11 of the C++11 standard for information on member access control. Here's an excerpt from ¶1...
A member of a class can be
private; that is, its name can be used only by members and friends of the class in which it is declared.
protected; that is, its name can be used only by members and friends of the class in which it is
declared, by classes derived from that class, and by their friends (see 11.4).
public; that is, its name can be used anywhere without access restriction.
Java
By default Java class is package-private.
C++
In C++ there is no visibility defined like Java.

Java Instance Variable Accessibility [duplicate]

This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 4 years ago.
What is the difference in the accessibility of the following variables in Java?
public class Joe {
public int a;
protected int b;
private int b;
int c;
}
I'm most interested in what the last one is doing.
public: read/writable for anyone
protected: read/writable for
instances of subclasses and from within the enclosing package
private: read/writable for any instance of the class
and inner or outer (enclosing) instance
int c:
package-private, read/writable for
all classes inside same package
See the JLS for more details
EDIT: Added the comment for protected stating that access is granted from inside same package, you guys are totally right. Also added comment for private. I remember now... ;-)
Sorry for answering corrections to one previous answer but I don't have enough reputation to modify directly...
public - read/writable for anyone
protected - read/writable for
instances subclasses and all classes
inside same package
int c : package-private,
read/writable for all classes inside
same package
private - read/writable for any member of that class itself and inner classes (if any)
It is better to order the access modifiers this way, from the broadest access (public) to the narrowest (private), knowing that when going from narrow to broad, you don't lose any possibilities.
That's particularly important for "protected", where it is often misunderstood that classes in the same package can also access protected members of a class (not only its subclasses).
I try to avoid package level access completely (the last access you mention).
I like to keep classes self-contained. If another class needs access to something in my class it should be public (and it should by a method, not an attribute). Otherwise I feel you've broken encapsulation, as explained in Abstraction VS Information Hiding VS Encapsulation.
And all of these are compile time protections, they can be readily overridden through reflection at runtime.

Categories

Resources