Private Protected

Private Protected



⚑ ALL INFORMATION CLICK HERE πŸ‘ˆπŸ»πŸ‘ˆπŸ»πŸ‘ˆπŸ»

































Private Protected


Sign up with email
Sign up




Sign up with Google



Sign up with GitHub



Sign up with Facebook




Asked
12 years, 3 months ago


java private public protected access-modifiers


31.2k 14 14 gold badges 127 127 silver badges 172 172 bronze badges


34.4k 4 4 gold badges 21 21 silver badges 21 21 bronze badges



private hides from other classes within the package. public exposes to classes outside the package. protected is a version of public restricted only to subclasses.

–  Museful
Feb 13 '13 at 9:56






@Tennenrishin β€” No ; contrary to C++, in Java protected makes the method also accessible from the whole package. This stupidity in Java's visiblity model breaks the goal of protected .

–  Nicolas Barbulesco
Aug 21 '13 at 9:51



@Nicolas It is accessible from the whole package, with or without protected . As an access modifier , all that protected does is to expose to subclasses outside the package.

–  Museful
Mar 14 '14 at 10:59






@tennenrishin - well, that is what Nicolas said... and you are just repeating it now. What you originally said was that protected - and I quote - 'is a version of public restricted only to subclasses' which is not true by your own admission since protected also allows access through the whole package (ergo, it does not restrict access to subclasses.)

–  luis.espinal
Apr 7 '14 at 13:45






I also agree with Nicolas in that the protected access mode in Java is idiotic. What happened is that Java conflated horizontal (lattice) and vertical access restriction qualifiers. Default scope is a horizontal/lattice restriction with the lattice being the package. Public is another horizontal restriction where the lattice is the whole world. Private and (C++) protected are vertical. It would have been better if we had a cross-cut access, say, protected-package for the rare cases where we actually needed it, leaving protected to be equivalent to the C++ version of protected.

–  luis.espinal
Apr 7 '14 at 13:53


1,460 10 10 silver badges 21 21 bronze badges


77.2k 10 10 gold badges 43 43 silver badges 66 66 bronze badges



The protected member can only be accessed from subclass of same package but not subclass from different package. There should be a correction in above table

–  niks
Sep 1 '17 at 8:35



I am still not able to differentiate between 'Public' and 'Protected'. And what is 'World' in this answer. Does it mean access out of project folder in a different project & package?? But that is not taking place. Need help on this.

–  Deepak
Apr 25 '18 at 12:25



World is within your project . I should explain further. Libraries are within your project, and if you're creating a library, they would expose these public classes and methods as well. So, saying just within your project is a bit off. "Everything that uses it" is a better description.

–  adprocas
May 3 '18 at 13:02



For example, if I have MyClass and I'm doing AnotherClass extends MyClass I will have access to all protected and public methods and properties from within AnotherClass . If I do MyClass myClass = new MyClass(); in AnotherClass somewhere - let's say the constructor - I will only have access to the public methods if it is in a different package. Note that if I do = new MyClass() { @Override protected void protectedMethod() { //some logic } }; it appears that I can access protected methods, but this kind of the same as extending it, but inline instead.

–  adprocas
May 4 '18 at 12:25



Unfortunately, this answer is a gross oversimplification. Reality is a bit more complicated, especially when you consider protected (which is actually quite a difficult access modifier to fully understand - most people who think they know what protected means really don't). Also, as Bohemian pointed out, it doesn't answer the question - it says nothing about when to use each access modifier. In my opinion, this answer isn't quite bad enough to downvote, but close. But over 4000 upvotes? How did this happen?

–  Dawood ibn Kareem
Jul 11 '18 at 6:26


708 4 4 silver badges 20 20 bronze badges


123k 20 20 gold badges 146 146 silver badges 285 285 bronze badges



friends -> "The less you know about it the better" ---> It gives selective visibility, which is still superior to package privacy. In C++, it has its uses, because not all functions can be member functions, and friends is better than public'ing. Of course there is a danger of misuse by evil minds.

–  Sebastian Mach
Jun 7 '11 at 10:13






It should also be noted that "protected" in C++ has a different meaning - a protected method is effectively private, but can still be called from an inheriting class. (As opposed to Java where it can be called by any class within the same package.)

–  Rhys van der Waerden
Oct 2 '11 at 12:34



@RhysvanderWaerden C# is the same as C++ in this aspect. I find it pretty odd that Java doesn't allow to declare a member that's accessible to the subclass but not the entire package. It's sort of upside down to me - a package is broader scope than a child class!

–  Konrad Morawski
Oct 15 '13 at 17:36






@KonradMorawski IMHO package is smaller scope than subclass. If you haven't declared your class final, users should be able to subclass it - so java protected is part of your published interface. OTOH, packages are implicitly developed by a single organization: e.g. com.mycompany.mypackage. If your code declares itself in my package, you implicitly declare yourself part of my organization, so we should be communicating. Thus, package publishes to a smaller/easier to reach audience (people in my company) than subclass (people who extend my object) and so counts as lower visibility.

–  Eponymous
May 22 '14 at 20:37






friend is good for defining special relationships between classes. It allows superior encapsulation in many cases when used correctly. For example it can be used by a privileged factory class to inject internal dependencies into a constructed type. It has a bad name because people who don't care about correctly maintaining a well designed object model can abuse it to ease their workload.

–  Dennis
Dec 8 '14 at 10:05


377k 94 94 gold badges 766 766 silver badges 793 793 bronze badges



Just saying: there are a lot of people who have problems with distinguishing red/green coloring. Tables using red/green (or yellow/orange/...) coloring schemes are rarely "better" at anything ;-)

–  GhostCat
Oct 11 '18 at 10:50






@GhostCat, I disagree. I think red/green aligns intuitively with "works"/"does not work" for many people, i.e. it is better than many alternatives.

–  aioobe
Nov 14 '18 at 14:10



colourblindawareness.org/colour-blindness/… ... The 8% of colour blind men can be divided approximately into 1% deuteranopes, 1% protanopes, 1% protanomalous and 5% deuteranomalous . And as I am one of those 50% of that 5%, rest assured: red/green sucks.

–  GhostCat
Nov 14 '18 at 14:13






@GhostCat Ok.. that's a larger part of the population than I expected. I uploaded the image in this color blindness simulator and tested all different modes. Even in monochromacy/achromatopsia mode the color difference is reasonable. Can you see the difference or is the simulator off? (I'm still of the opinion that red/green is very intuitive for color seeing people.)

–  aioobe
Nov 14 '18 at 14:32






I can see the difference, but I am also able to pass half of the color blindness tests that we have to do in Germany for the drivers licence ;-) ... but I think such a simulator is "good enough".

–  GhostCat
Nov 14 '18 at 14:40


____________________________________________________________________
| highest precedence <---------> lowest precedence
*β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”
\ xCanBeSeenBy | this | any class | this subclass | any
\ __________ | class | in same | in another | class
\ | nonsubbed | package | package |
Modifier of x \ | | | |
β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”*β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”
public | βœ” | βœ” | βœ” | βœ”
β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”
protected | βœ” | βœ” | βœ” | ✘
β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”
package - private | | | |
( no modifier ) | βœ” | βœ” | ✘ | ✘
β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”+β€”β€”β€”β€”β€”β€”β€”
private | βœ” | ✘ | ✘ | ✘
____________________________________________________________________



22.5k 21 21 gold badges 113 113 silver badges 158 158 bronze badges



It is worth putting in words - "Protected modifier makes the object available across other packages, whereas default/no-modifier restricts access to the same package"

–  vanguard69
Aug 15 '16 at 16:53



@vanguard69, the protected modifier makes the marked thing (class, method, or field) available to some other class in some other package only iff said other class is a subclass of the class where that protected - marked thing is declared.

–  Abdull
Aug 15 '16 at 18:14



"nonsubbed"? "this subclass in another package"? Huh. I thought I knew Java.

–  sehe
Dec 10 '17 at 12:24



@AlexanderFarber did you optimize for a particular browser config? This is my chrome now and this is Firefox

–  sehe
Dec 10 '17 at 12:29



Hmm let's revert my change then

–  Alexander Farber
Dec 10 '17 at 14:26


19.9k 4 4 gold badges 36 36 silver badges 49 49 bronze badges


15.9k 8 8 gold badges 29 29 silver badges 40 40 bronze badges



@RuchirBaronia, "world" = all code in the application, regardless where it is.

–  Andrejs
Feb 26 '16 at 19:12


26k 14 14 gold badges 82 82 silver badges 106 106 bronze badges



"modifiers other than public are forbidden" β€” as of Java 9, this is no longer the case: interfaces can also have private methods.

–  MC Emperor
Aug 25 '18 at 20:34


10.4k 11 11 gold badges 39 39 silver badges 42 42 bronze badges


28.1k 40 40 gold badges 106 106 silver badges 158 158 bronze badges


105k 61 61 gold badges 294 294 silver badges 388 388 bronze badges



Object#clone() is an example of a protected member.

–  Eng.Fouad
Nov 15 '13 at 20:08



What is the difference between doing super.foo() and the first invalid situation f.foo() ?

–  cst1992
Oct 28 '17 at 9:18



@cst1992 It's confusing but see the Java Language Specification 6.6.2: "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". With super.foo() the reference "super" is "directly responsible for the implementation" but the reference "f" is not. Why? Because you can be 100% certain that "super" is of type Father, but not for "f"; at run-time it could be some other sub-type of Father. See docs.oracle.com/javase/specs/jls/se9/html/…

–  skomisa
Jan 30 '18 at 17:55



It's refreshing to read an answer from someone who understands protected . Unfortunately, all the other answers on this page that define protected get it a little bit wrong.

–  Dawood ibn Kareem
Jul 11 '18 at 6:20


11.2k 3 3 gold badges 34 34 silver badges 48 48 bronze badges


43.8k 25 25 gold badges 92 92 silver badges 147 147 bronze badges


27.5k 21 21 gold badges 93 93 silver badges 123 123 bronze badges


631 6 6 silver badges 17 17 bronze badges


27.5k 21 21 gold badges 93 93 silver badges 123 123 bronze badges


2,488 2 2 gold badges 17 17 silver badges 26 26 bronze badges


2,273 22 22 silver badges 31 31 bronze badges


2,379 2 2 gold badges 22 22 silver badges 40 40 bronze badges


417 4 4 silver badges 9 9 bronze badges


27.5k 21 21 gold badges 93 93 silver badges 123 123 bronze badges


932 1 1 gold badge 15 15 silver badges 26 26 bronze badges


27.5k 21 21 gold badges 93 93 silver badges 123 123 bronze badges


470 7 7 silver badges 9 9 bronze badges



Just to add this "Once the child gets access to the parent class’s protected member, it becomes private (or rather I would say a special private member which can be inherited by the subclasses of the subclass) member of the subclass."

–  Anand
Oct 27 '12 at 18:55


27.5k 21 21 gold badges 93 93 silver badges 123 123 bronze badges


2,506 16 16 silver badges 13 13 bronze badges


11.2k 5 5 gold badges 86 86 silver badges 84 84 bronze badges


21.4k 9 9 gold badges 53 53 silver badges 76 76 bronze badges



what exactly is the supplement, and why is it not an edit to the existing post?

–  sehe
Nov 17 '16 at 15:39



the supplement is Access Modifiers. Why not an edit? To keep the accepted answer unaltered for historical sake and to give my answer.

–  Χ™Χ©Χ• אוהב אוΧͺך
Nov 18 '16 at 2:25





111 1 1 silver badge 7 7 bronze badges



Default is not an access modifier, and two of the others are misspelt.

–  user207421
Sep 24 '16 at 3:13


71 1 1 silver badge 9 9 bronze badges


135 1 1 silver badge 10 10 bronze badges



For more clarity, no modifier == package private | package protected

–  ahmednabil88
Dec 18 '20 at 20:56





14.9k 10 10 gold badges 67 67 silver badges 89 89 bronze badges


1,458 4 4 gold badges 20 20 silver badges 29 29 bronze badges


13.1k 2 2 gold badges 70 70 silver badges 74 74 bronze badges


644 7 7 silver badges 10 10 bronze badges



The question was about Java, not C++.

–  Benoit
Sep 20 '19 at 8:57



@Benoit But what I have posted , the pictures in special , are not the same for both :java and c++ ?this rules are not applying for java too ? thanks

–  leonidaa
Sep 22 '19 at 10:31






In C++ there are only 3 modifiers, while there are 4 in java.

–  Benoit
Sep 23 '19 at 9:15



the analogy is good, but default access specifier is missing,

–  mss
Jan 3 '20 at 9:54



OP asked the question "What is the difference between public, protected, package-private and private in Java?"

–  JL_SO
Apr 9 '20 at 21:00


93 1 1 silver badge 6 6 bronze badges


Highly active question . Earn 10 reputation in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.


JPMorgan Chase Bank, N.A. Moscow, Russia
Senior Full Stack Engineer (Remote OR NYC)
Senior Software Engineer, Front-end Focused
Senior Full Stack Developer (Cloud)
Allogy Interactive No office location

Stack Overflow

Questions
Jobs
Developer Jobs Directory
Salary Calculator
Help
Mobile
Disable Responsiveness


Products

Teams
Talent
Advertising
Enterprise



Company

About
Press
Work Here
Legal
Privacy Policy
Terms of Service
Contact Us



Stack Exchange Network

Technology
Life / Arts
Culture / Recreation
Science
Other


Join Stack Overflow to learn, share knowledge, and build your career.
In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public , protected and private , while making class and interface and dealing with inheritance?
The official tutorial may be of some use to you.
(Caveat: I am not a Java programmer, I am a Perl programmer. Perl has no formal protections which is perhaps why I understand the problem so well :) )
Like you'd think, only the class in which it is declared can see it.
It can only be seen and used by the package in which it was declared. This is the default in Java (which some see as a mistake).
Package Private + can be seen by subclasses or package members.
Visible outside the code I control. (While not Java syntax, it is important for this discussion).
C++ defines an additional level called "friend" and the less you know about that the better.
When should you use what? The whole idea is encapsulation to hide information. As much as possible you want to hide the detail of how something is done from your users. Why? Because then you can change them later and not break anybody's code. This lets you optimize, refactor, redesign, and fix bugs without worry that someone was using that code you just overhauled.
So, the rule of thumb is to make things only as visible as they have to be. Start with private and only add more visibility as needed. Only make public that which is absolutely necessary for the user to know, every detail you make public cramps your ability to redesign the system.
If you want users to be able to customize behaviors, rather than making internals public so they can override them, it's often a better idea to shove those guts into an object and make that interface public. That way they can simply plug in a new object. For example, if you were writing a CD player and wanted the "go find info about this CD" bit customizable, rather than make those methods public you'd put all that functionality into its own object and make just your object getter/setter public. In this way being stingy about exposing your guts encourages good composition and separation of concerns
Personally, I stick with just "private" and "public". Many OO languages just have that. "Protected" can be handy, but it's really a cheat. Once an interface is more than private it's outside of your control and you have to go looking in other people's code to find uses.
This is where the idea of "published" comes in. Changing an interface (refactoring it) requires that you find all the code which is using it and change that, too. If the interface is private, well no problem. If it's protected you have to go find all your subclasses. If it's public you have to go find all the code which uses your code. Sometimes this is possible, for example, if you're working on corporate code that's for internal use only it doesn't matter if an interface is public. You can grab all the code out of the corporate repository. But if an interface is "published", if there is code using it outside your control, then you're hosed. You must support that interface or risk breaking code. Even protected interfaces can be considered published (which is why I don't bother with protected).
Many languages find the hierarchical nature of public/protected/private to be too limiting and not in line with reality. To that end, there is the concept of a trait class , but that's another show.
Here's a better version of the table, that also includes a column for modules.

A private member ( i ) is only accessible within the same class as it is declared.
A member with no access modifier ( j ) is only accessible within classes in the same package.
A protected member ( k ) is accessible within all classes in the same package and within subclasses in other packages.
A public member ( l ) is accessible to all classes (unless it resides in a module that does not export the package it is declared in).
Access modifiers is a tool to help you to prevent accidentally breaking encapsulation (*) . Ask yourself if you intend the member to be something that's internal to the class, package, class hierarchy or not internal at all, and choose access level accordingly.
Easy rule. Start with declaring everything private. And then progress towards the public as the needs arise and design warrants it.
When exposing members ask yourself if you are exposing representation choices or abstraction choices. The first is something you want to avoid as it will introduce too many dependencies on the actual representation rather than on its observable behavior.
As a general rule I try to avoid overriding method implementations by subclassing; it's too easy to screw up the logic. Declare abstract protected methods if you intend for it to be overridden.
Also, use the @Override annotation when overriding to keep things from breaking when you refactor.
It's actually a bit more complicated than a simple grid shows. The grid tells you whether an access is allowed, but what exactly constitutes an access? Also, access levels interact with nested classes and inheritance in complex ways.
The "default" access (specified by the absence of a keyword) is also called package-private . Exception: in an interface, no modifier means public access; modifiers other than public are forbidden. Enum constants are always public.
Is an access to a member with this access specifier allowed?
Local variables and formal parameters cannot take access specifiers. Since they are inherently inaccessible to the outside according to scoping rules, they are effectively private.
For classes in the top scope, only public and package-private are permitted. This design choice is presumably because protected and private would be redundant at the package level (there is no inheritance of packages).
All the access specifiers are possible on class members (constructors, methods and static member functions, nested classes).
The access specifiers can be strictly ordered
public > protected > package-private > private
meaning that public provides the most access, private the least. Any reference possible on a private member is also valid for a package-private member; any reference to a package-private member is valid on a protected member, and so on. (Giving access to protected members to other classes in the same package was considered a mistake.)
You also have to consider nested scopes, such as inner classes. An example of the complexity is that inner classes have members, which themselves can take access modifiers. So you can have a private inner class with a public member; can the member be accessed? (See below.) The general rule is to look at scope and think recursively to see whether you can access each level.
However, this is quite complicated, and for full details, consult the Java Language Specification . (Yes, there have been compiler bugs in the past.)
For a taste of how these interact, consider this example. It is possible to "leak" private inner classes; this is usually a warning:
As a result, if we divide access right into three rights:
The most misunderstood access modifier in Java is protected . We know that it's similar to the default modifier with one exception in which subclasses can see it. But how? Here is an example which hopefully clarifies the confusion:
Assume that we have 2 classes; Father and Son , each in its own package:
Let's add a protected method foo() to Father .
The method foo() can be called in 4 contexts:
Inside a class that is located in the same package where foo() is defined ( fatherpackage ):
Inside a subclass, on the current instance via this or super :
On an reference whose type is the same class:
On an reference whose type is the parent class and it is inside the package where foo() is defined ( fatherpackage ) [This can be included inside context no. 1]:
The following situations are not valid.
On an reference whose type is the parent class and it is outside the package where foo() is defined ( fatherpackage ):
A non-subclass inside a package of a subclass (A subclass inherits the protected members from its parent, and it makes them private to non-subclasses):
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces.
Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
A class, method, constructor, interface etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.
Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.
A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.
We cannot Override the Static fields.if you try to override it does not show any error
but it doesnot work what we except.
The difference can be found in the links already provided but which one to use usually comes down to the "Principle of Least Knowledge". Only allow the least visibility that is needed.
Private : Limited access to class only
Default (no modifier) : Limited access to class and package
Protected : Limited access to class, package and subclasses (both inside and outside package)
Public : Accessible to class, package (all), and subclasses... In short, everywhere.
Access modifiers are there to restrict access at several levels.
Public: It is basically as simple as you can access from any class whether that is in same package or not.
To access if you are in same package you can access directly, but if you are in another package then you can create an object of the class.
Default: It is accessible in the same package from any of the class of package.
To access you can create an object of the class. But you can not access this variable outside of the package.
Protected: you can access variables in same package as well as subclass in any other package.
so basically it is default + Inherited behavior.
To access protected field defined in base class you can create object of child class.
Private: it can be access in same class.
In non-static methods you can access directly because of this reference (also in constructors)but to access in static methods you need to create object of the class.
Java access modifiers are used to provide access control in Java.
Accessible to the classes in the same package only.
This access is more restricted than public and protected, but less restricted than private.
Can be accessed from anywhere. (Global Access)
Accessible only inside the same class.
If you try to access private members on one class in another will throw compile error. For example,
Accessible only to the classes in the same package and to the subclasses
public - accessible from anywhere in the application.
protected - accessible from package and sub-classes in other package.
as well
private - accessible from its class only.
Visible to the package. The default. No modifiers are needed.
Visible to the class only ( private ).
Visible to the package and all subclasses ( protected ).
Variables and methods can be declared without any modifiers that are called. Default examples:
Methods, variables and constructors that are declared private can only be accessed within the declared class itself. The private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.
A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java universe.
However, if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.
Protected access modifier - protected:
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in another package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
....
Protected: Protected access modifier is the a little tricky and you can say is a superset of the default access modifier. Protected members are same as the default members as far as the access in the same package is concerned. The difference is that, the protected members are also accessible to the subclasses of the class in which the member is declared which are outside the package in which the parent class is present.
But these protected members are β€œaccessible outside the package only through inheritanceβ€œ. i.e you can access a protected member of a class in its subclass present in some other package directly as if the member is present in the subclass itself. But that protected member will not be accessible in the subclass outside the package by using parent class’s reference.
....
David's answer provides the meaning of each access modifier. As for when to use each, I'd suggest making public all classes and the methods of each class that are meant for external use (its API), and everything else private.
Over time you'll develop a sense for when to make some classes package-private and when to declare certain methods protected for use in subclasses.
Java access modifies which you can use
Access modifier can be applicable for class , field [About] , method . Try to access, subclass or override this.
Top level class(first level scope) can be public and default . Nested class [About] can have any of them
package is not applying for package hierarchy
Note: This is just a supplement for the accepted answer.
This is related to Java Access Modifiers .
A Java access modifier specifies which classes can access a given
class and its fields, constructors and methods. Access modifiers can
be specified separately for a class, its constructors, fields and
methods. Java access modifiers are also sometimes referred to in daily
speech as Java access specifiers, but the correct name is Java access
modifiers. Classes, fields, constructors and methods can have one of
four different Java access modifiers:
Access level modifiers determine whether other classes can use a
particular field or invoke a particular method. There are two levels
of access control:
A class may be declared with the modifier public, in which case that
class is visible to all classes everywhere. If a class has no modifier
(the default, also known as package-private), it is visible only
within its own package
The following table shows the access to members permitted by each
modifier.
The first data column indicates whether the class itself has access to
the member defined by the access level. As you can see, a class always
has access to its own members. The second column indicates whether
classes in the same package as the class (regardless of their
parentage) have access to the member. The third column indicates
whether subclasses of the class declared outside this package have
access to the member. The fourth column indicates whether all classes
have access to the member.
Access levels affect you in two ways. First, when you use classes that
come from another source, such as the classes in the Java platform,
access levels determine which members of those classes your own
classes can use. Second, when you write a class, you need to decide
what access level every member variable and every method in your class
should have.
Public Protected Default and private are access modifiers.
They are meant for encapsulation, or hiding and showing contents of the class.
Private is not accessible outside the class
Default is accessible only in the package.
Protected in package as well as any class which extends it.
Public is open for all.
Normally, member variables are defined private, but member methods are public.
Often times I've realized that remembering the basic concepts of any language can made possible by creating real-world analogies. Here is my analogy for understanding access modifiers in Java:
Let's assume that you're a student at a university and you have a friend who's coming to visit you over the weekend. Suppose there exists a big statue of the university's founder in the middle of the campus.
When you bring him to the campus, the first thing that you and your friend sees is this statue. This means that anyone who walks in the campus can look at the statue without the university's permission. This makes the statue as PUBLIC .
Next, you want to take your friend to your dorm, but for that you need to register him as a visitor. This means that he gets an access pass (which is the same as yours) to get into various buildings on campus. This would make his access card as PROTECTED .
Your friend wants to login to the campus WiFi but doesn't have the any credentials to do so. The only way he can get online is if you share your login with him. (Remember, every student who goes to the university also possesses these login credentials). This would make your login credentials as NO MODIFIER .
Finally, your friend wants to read your progress report for the semester which is posted on the website. However, every student has their own personal login to access this section of the campus website. This would make these credentials as PRIVATE .
This image will make you understand easily about the basic differences between public, private, protected and default access modifiers. The default modifier takes place automatically when you don't declare ant access modifiers in your code.
When you are thinking of access modifiers just think of it in this way (applies to both variables and methods ):
public --> accessible from every where
private --> accessible only within the same class where it is declared
Now the confusion arises when it comes to default and protected
default --> No access modifier keyword is present. This means it is available strictly within the package of the class. Nowhere outside that package it can be accessed.
protected --> Slightly less stricter than default and apart from the same package classes it can be accessed by sub classes outside the package it is declared.
class -> a top level class cannot be private. inner classes can be private which are accessible from same class.
instance variable -> accessible only in the class. Cannot access outside the class.
class -> a top level class can be package-private. It can only be accessible from same package. Not from sub package, not from outside package.
instance variable -> accessible from same package. Not from sub package, not from outside package.
class -> a top level class cannot be protected.
instance variable -> Only accessible in same package or subpackage. Can only be access outside the package while extending class.
class -> accessible from package/subpackage/another package
instance variable -> accessible from package/subpackage/another package
It is all about encapsulation (or as Joe Phillips stated, least knowledge ).
Start with the most restrictive (private) and see if you need less restrictive modifiers later on.
We all use method and member modifiers like private, public, ... but one thing too few developers do is use packages to organize code logically.
For example:
You may put sensitive security methods in a 'security' package.
Then put a public class which accesses some of the security related code in this package but keep other security classes package private .
Thus other developers will only be able to use the publicly available class from outside of this package (unless they change the modifier).
This is not a security feature, but will guide usage.
Another thing is that classes which depend a lot on each other may end up in the same package and could eventually be refactored or merged if the dependency is too strong.
If on the contrary you set everything as public it will not be clear what should or should not be accessed, which may lead to writing a lot of javadoc (which does not enforce anything via the compiler...).
Following block diagram explain how data members of base class are inherited when derived class access mode is private .
Note: Declaring data members with private access specifier is known as data hiding.
If a class member is declared with public then it can be accessed from anywhere
If a class member is declared with keyword protected then it can be accessed from same class members, outside class members within the same package and inherited class members. If a class member is protected then it can NOT be accessed from outside package class unless the outside packaged class is inherited i.e. extends the other package superclass. But a protected class member is always available to same package classes it does NOT matter weather the same package class is inherited or NOT
In Java default is NOT an access modifier keyword. If a class member is declared without any access modifier keyword then in this case it is considered as default member. The default class member is always available to same package class members. But outside package class member can NOT access default class members even if outside classes are subclasses unlike protected members
If a class member is declared with keyword protected then in this case it is available ONLY to same class members
Access Specifiers in Java:
There are 4 access specifiers in java, namely private, package-private (default), protected and public in increasing access order.
Private :
When you are developing some class and you want member of this class not to be exposed outside this class then you should declare it as private. private members can be accessed only in class where they are defined i.e. enclosing class. private members can be accessed on 'this' reference and also on other instances of class enclosing these members, but only within the definition of this class.
Package-private (default) :
This access specifier will provide access specified by private access specifier in addition to access described below.
When you are developing some package and hence some class (say Class1) within it, you may use default (need not be mentioned explicitly) access specifier, to expose member within class, to other classes within your (same) package. In these other classes (within same package), you can access these default members on instance of Class1. Also you can access these default members within subclasses of Class1, say Class2 (on this reference or on instance of Class1 or on instance of Class2).
Basically, within same package you can access default members on instance of class directly or on 'this' reference in subclasses.
protected :
This access specifier will provide access specified by package-private access specifier in addition to access described below.
When you are developing some package and hence some class (say Class1) within it, then you should use protected access specifier for data member within Class1 if you don't want this member to be accessed outside your package (say in package of consumer of your package i.e. client who is using your APIs) in general, but you want to make an exception and allow access to this member only if client writes class say Class2 that extends Class1. So, in general, protected members will be accessible on 'this' reference in derived classes i.e. Class2 and also on explicit instances of Class2.
So bottom line is, protected members can be accessed in other packages, only if some class from this other package, extends class enclosing this protected member and protected member is accessed on 'this' reference or explicit instances of extended class, within definition of extended class.
public : This access specifier will provide access specified by protected access specifier in addition to access described below.
When you are developing some package and hence some class (say Class1) within it, then you should use public access specifier for data member within Class1 if you want this member to be accessible in other packages on instance of Class1 created in some class of other package. Basically this access specifier should be used when you intent to expose your data member to world without any condition.
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo Β© 2021 Stack Exchange Inc; user contributions licensed under cc by-sa . revΒ 2021.2.2.38474


private protected - C# Reference | Microsoft Docs
What is the difference between public, protected , package- private and...
Difference between Private and Protected in C++ with... - GeeksforGeeks
Private Protected Access Modifier In C#
C++ для Π½Π°Ρ‡ΠΈΠ½Π°ΡŽΡ‰ΠΈΡ… private , public, protected ΠΊΠ°ΠΊ ΠΌΠΎΠ΄ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€Ρ‹ для...
Difference between Private and Protected in C++ with Example




Last Updated :
18 Oct, 2019



Β Β Β Β Β Β Β Β  // Child class is able to access the inherited
Β Β Β Β Β Β Β Β  // protected data members of the base class
Β Β Β Β Β Β Β Β  cout << "id_protected is: "
Β Β Β Β Β Β Β Β Β Β Β Β Β  << id_protected << endl;
Β Β Β Β  // member function of the derived class can
Β Β Β Β  // access the protected data members of the base class
// C++ program to demonstrate private
Β Β Β Β  void compute_area( double r)
Β Β Β Β Β Β Β Β  // member function can access private
Β Β Β Β Β Β Β Β  double area = 3.14 * radius * radius;
Β Β Β Β Β Β Β Β  cout << "Radius is: " << radius << endl;
Β Β Β Β Β Β Β Β  cout << "Area is: " << area;
Β Β Β Β  // creating object of the class
Β Β Β Β  // trying to access private data member
How to access private/protected method outside a class in C++
Public vs Protected in C++ with Examples
Protected keyword in Java with examples
Can we access private data members of a class without using a member or a friend function?
Can a constructor be private in C++ ?
Publicly inherit a base class but making some of public method as private
How to call private method from another class in Java with help of Reflection API?
Can virtual functions be private in C++?
Similarities and Difference between Java and C++
asin() and atan() functions in C/C++ with Example
Difference between "int main()" and "int main(void)" in C/C++?
What’s difference between β€œarray” and β€œ&array” for β€œint array[5]” ?
Difference between C structures and C++ structures
Difference between strlen() and sizeof() for string in C
Difference between const char *p, char * const p and const char * const p
Difference between Relational operator(==) and std::string::compare() in C++
Difference between std::remove and vector::erase for vectors
Difference between namespace and class
Difference between strncmp() and strcmp in C/C++
Difference between std::swap and std::vector::swap
Difference between fundamental data types and derived data types
Difference between std::quick_exit and std::abort
Difference between continue and break statements in C++


favorite_border
Like




Program to print the Diagonals of a Matrix


Program to print the Ladder Pattern


Easy
Normal
Medium
Hard
Expert

Data Structures and Algorithms – Self Paced Course
Ad-Free Experience – GeeksforGeeks Premium



5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305




Company
About Us
Careers
Privacy Policy
Contact Us
Copyright Policy


Learn
Algorithms
Data Structures
Languages
CS
Subjects
Video Tutorials


Practice
Courses
Company-wise
Topic-wise
How to begin?


Contribute

Write an Article
Write Interview
Experience
Internships
Videos




@geeksforgeeks
, Some rights reserved

Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.
The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.
Difference between Private and Protected
Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.
Writing code in comment?
Please use ide.geeksforgeeks.org ,
generate link and share the link here.

The class members declared as private can be accessed only by the functions inside the class.
Protected access modifier is similar to that of private access modifiers.
Only the member functions or the friend functions are allowed to access the private data members of a class.
The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.

Matures Porn Online
Zoo Peeing
Overwatch Hentai Gif
Bella Thorne Naked Peeing Fakes
Vaginal Penetration

Report Page