Java Instance Variable Accessibility [duplicate] - java

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.

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".

public, private and regular variable [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.
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.

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.

Oracle Java 7 Certification: The private and protected access modifiers can be used with which entities?

I am experimenting the questions from Oracle for the Java 7 Associate certification. The application for the windows is created by Oracle Press (probably). They've sent it to me with the Book.
Currently, I have one question which application says "wrong answer", when I say that all answers are correct. Could someone explain this? The question is that Inner classes and inner interfaces can be both private and protected, but the explanation says classes and interfaces can't be. Please find question and explanation below. I hope this is the right place to ask this kind of questionJ.
Question
The private and protected access modifiers can be used with which entities? (Choose all that apply.)
Answers:
A: Classes
B: Interfaces
C: Constructors
D: Methods
E: Data Members
Correct Answers from Oracle:
C: Constructors
D: Methods
E: Data members
EXPLANA TION:
C, D, and E. The private and protected access modifiers can be used with constructors, methods, and data members.
A and B are incorrect. The private and protected access modifiers cannot be used with classes and interfaces.
The question is that Inner classes and inner interfaces can be both private and protected
Yes you are right. But we should treat them as Data Members of that Class which they are presented. Since they are not individual classes,interfaces we should not say them.
Ofcourse in the explanation they must mention the word TOP LEVEL. Absence of that causing the confusion here.
I guess the trick here is that the question doesn't take inner classes and interfaces into account. Answers A and B only refer to top-level class and interface declarations (although not explicitly stated).

access modifiers 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 9 years ago.
Edited to fix being marked as duplicate or to be more clear on why it appears to be a duplicate. At the time I did not know that package and default where the same thus reason for this post.
now I going through exam questions in preparation for my Java exam and I have a question asking me to explain access modifiers and its asking me about a Package modifier.
I can find info on private, Protected, public and default but can't find anything on Package.
can someone please give me an answer or link me to an article about it?
package-private is not a real modifier. You can't type package-private and get the system to recognize it as an access modifier. It's really the default, made by not including any other modifiers.
It means that the given members can only be accessed in the same package.
For example, com.hexafraction.Cow can access a member with default modifiers(none actually) in com.hexafraction.Dog, but com.foo.Crow can't access that member as it's not in the same pacakge.
In this example, the following makes up Cow:
pacakge com.hexafraction;
class Cow{
void moo(){ //no public, protected, or private modifier
System.out.println("moo!");
}
}
Edit for the future: In Java 8, package will supposedly be the modifier needed for this. Literally typing default will still not apply here.
The so-called "package-private" access level is what occurs without a modifier such as private, protected, or public.
Example:
public class Test {
int test; // package-private
}
Anything in the same package, even an unrelated class, can access it, but other classes (even subclasses of the class) outside of the package cannot access it.
This link to the Java tutorial on the subject should help.

Categories

Resources