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.
Ok so I thought the point of having protected fields was so that the variable was accessible by only the subclass and the class having the protected fields. Making objects of either the subclass or the superclass should not grant access to these fields. If I am correct, how come code like this is compiling correctly?
//superclass
public class SuperClass{
protected int x = 5;
}
//main class with main method
public class MainClass{
public static void main(String[] args) {
SuperClass a = new SuperClass();
a.x = 8;
System.out.println(a.a);
}
}
This will print out 8, which means I modified a protected variable outside of the classes which have them...
protected variables and methods are accessible from other classes of the same package as well as subclasses of the current class.
private variables and method are only accessible from within the current class.
If there is no modifier (none of protected, private or public), then by default the variable is accessible from any classes within the same package but not from subclasses.
see here for the official documentation
protected members in Java are also visible to other classes in the package.
Move your main() method to a different package and you'll get an error.
I thought the point of having protected fields was so that the variable was accessible by only the subclass and the class having the protected fields.
You thought wrongly.
Making objects of either the subclass or the superclass should not grant access to these fields.
It does. NB You are now contradicting your own thought here. Your thought includes the subclass, and now you're trying to exclude it.
If I am correct
You aren't.
Related
This question already has answers here:
Why can't a class or an interface receive private or protected access modifiers?
(3 answers)
Closed 6 years ago.
It may be a repeated question.
But i need a clear answer for this answer.
I am so confused.
For EG:
I have class to display time.
import java.util.Date;
**public** class DateDisplay {
public static void main(String[] args) {
Date today = new Date();
System.out.println(today);
}
}
None of the class in the same package is going to extend this class.
Why can not i declare a class at private?
Why JAVA is not allowing me to declare a class as private? What is the reason behind this?
My second question is where should i use inner class?
What is purpose of inner class?
To answer the first question: If you want to get this done define a public/protected class with in it a private class. As a result the private class is only accessible within its class.
Example:
public class x
{
private class y
{
}
}
Here class y is only accessible in class x
I guess this also answers your second question,
see for more info
https://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
Access modifiers on a class do not only specify where you can extend the class; they also specify where the class can be used.
private means: accessible only inside the class itself. It would not make sense for a top-level class to be private, because that would mean you could not use the class at all - any other classes would't be able to use it.
If you want to make a class inaccessible to classes outside the package, then use the default access level (don't specify an access modifier at all):
// Only accessible within the same package
class DateDisplay {
// ...
}
Note however, that a class with a main method should be public.
This question already has answers here:
Using a private variable in a inherited class - Java
(3 answers)
Closed 6 years ago.
I have two classes, class A and class B which extends class A.
We say that you cannot access private members of the superclass. Let's say that class A has a public method which returns the private member. Now, if we create an instance of class B and call that method, we can actually see that it could access the private member. Why does this happen?
Still you are accessing it's public member (method), no matter what it's internal implementation. You cannot access private members directly, that is what it mean.
Class A has access to the private variable, and class B has access to the getX method. When you call A.getX(), class A passes on the value of x. Think of it like a proxy. You don't have access to that object, but you can route your request through something that does.
By adding the getter method to class A you have changed the contract exposed by A to allow all other classes read-only access that member. Having only a getter does not allow anybody else (including the subclass) to modify the private member, only read it.
There's no particular reason a subclass should be limited in a way that other classes are not.
The private public protected and default modifiers define on which scope a component is accessible, getX() is defined in the scope of class A, for which x is defined private hence it can access x.
This question already has answers here:
Should we declare a public constructor when the class is declared as package private?
(2 answers)
Closed 8 years ago.
I am new to Java. I want to know what it is the use of public constructor in a private class. Private class inside the class can be initialized from the same class then what it is the use to make the constructor of private class to public?
public class MainActivity extends Activity {
private class AcceptThread extends Thread {
public AcceptThread() {
}
}
}
There doesn't seems to be any real use case for public or protected modifiers with private classes. If you have multiple classes in a single file though (but not nested or local), you need non-private constructors to instantiate the private classes.
// X.java
public class X {
private Y y = new Y();
}
class Y {
Y () {
// if this were private, X wouldn't be able to create an instance of Y
}
}
Actually default or protected visibility would be enough to create an instance in this case. All non-private modifiers allow you to create instances from other classes within the same package but practically have the same visibility.
The private class isn't visible to classes outside of the package, so public methods have no use here.
The private class can't be extended by classes outside of the package, so protected has no use either.
Even when using reflections, a public constructor is not accessible by default from other packages and will throw a IllegalAccessException. It checks the class visibility first, then the member visibility.
The default modifier is the most restrictive modifier that allows you to directly call the constructor from other classes, so package-private seems to be the most appropriate visibility for the constructor and also any other non-private methods. This also has the advantage that if you change the class visibility in the future, you don't accidentally expose the constructor or any methods to the public.
You know, I ask myself this question almost each time I make a private inner class, but I always assumed that there could be some (possibly contrived) reason for a public constructor. So #kapep 's answer got me tingling and encouraged to find ways to require a public constructor on a private inner class, but the more I think and experiment with it, the more I think the holes are plugged.
Possible angles, all of which failed me:
Serialisation: When unmarshalling an object whose superclass is not serializable, the superclass needs a no-arg constructor accessible from the subclass. So, protected should always suffice here.
Reflective tools: Code that uses reflection to get the inner class constructor through a returned instance. Fails because the type visibility is checked first, as #kapep pointed out, though it leaves a rather interesting error message:
Exception in thread "main" java.lang.IllegalAccessException: Class A can not access a member of class contrived.B$C with modifiers "public"
Inner class extension shenanigans: Don't try this at home:
package a;
class Outer {
private class Inner {
}
}
package b;
// compile error: Outer.Inner has private access in Outer
class Extender extends a.Outer.Inner {
Extender(a.Outer outer) {
outer.super();
}
}
Seemed promising at first, but I didn't get too far with that one.
In the end, I could not find a way to make a public constructor on a private inner class useful.
Then why is this technically legal despite having no use? Probably because the compiler automagically inserts a no-arg public constructor when no other constructor is provided. Hence the language should not disallow this constructs. More of an artefact than a reason, though.
This question already has answers here:
Java protected fields vs public getters
(8 answers)
Closed 9 years ago.
my question is concerning about the "protected" access modifier.
I know its functionality, but I don't know when I need to use it.
Conceptually methods in a class could be divided as:
constructors
setters/getters
methods used from clients (i.e other classes)
internal methods (used from other methods in the class)
You use protected when
Your class is designed for inheritance - You expect the users of your library to inherit from the class that you are designing. Very often the class will be abstract.
The class provides special functionality to its derived classes that must not be visible to other classes - You know that derived classes must have access to information that would otherwise be private, or
The derived classes must provide functionality to the base class - See Template Method Pattern for information about this use of protected methods.
Note that protected methods are similar to public methods in the sense that once you put them in, they need to stay in for as long as you support your library. Unlike private methods that you can freely remove, protected methods remain a part of the interface of your class.
Use it when you need to do some internal stuff that is not exposed in public API but still needs to be overriden by subclasses.
You need to use the protected access modifier, when you want the descendant class to see the fields / methods of the super class, BUT you do not want other classes to see these.
One situation I've found it useful in is when a superclass's method is intended to call a subclass's method, e.g.
public abstract class SuperClass
public final void exposedMethod {
hiddenMethod();
}
abstract protected void hiddenMethod();
}
public class SubClass extends SuperClass {
protected void hiddenMethod() { }
}
In this case exposedMethod takes care of things like logging and retry logic, while hiddenMethod is the actual method implementation
A lot of classes in the java api use protected constructers so that you can only have instances of objects from other objects. Example: The Graphics class. It has a protected constructor, and a way to obtain a copy of the Graphics class is to have a Image object to call getGraphics() on.
A primary usage of protected methods is when a class expects its derived classes to override the method with its own features, and also call the base class version.
E.g.
public class Base
{
public void doStuff()
{
a(); b(); c();
}
protected void a(){ //does something
}
protected void b(){ //does something
}
protected void c(){ //does something
}
}
...
public class Derived extends Base
{
protected void b()
{
// Does something different before the original functionality.
super.b(); // Calls the original functionality
// Does something different after the original functionality.
}
}
...
public class Main
{
public static void main(String args[])
{
Base b = new Derived();
b.doStuff(); // Calls b.a(), ((Derived)b).b(), b.c()
}
}
You should always encapsulate your code to restrict access to the meet the exact level of access needed. Use the protected modifier when you need to only allow access to the code within the package or when its subclassed. I don't get what you mean by...
Conceptually methods in a class could be divided as: constructors setters/getters methods used from clients (i.e other classes) internal methods (used from other methods in the class)
Just put the access modifier infront of what you need to be labeled as "protected".
Is there an info-graphic that explains java variable inheritance and constructor code flow?
I'm having troubles visualizing how inheritance and class variables work, public, static private default or otherwise.
The Java Tutorials from Oracle have a section all about Inheritance and should be able to answer most of your questions.
I would refer you to go with Lava Language Specification and try to write the code using above keywords and then test it.
default: Visible to the package. .
private: Visible to the class only
public: Visible to the world
protected: Visible to the package and all subclasses .
The access modifier (public, protected, package) plays only a small role in inheritance. You can't make a function or variable in a subclass less accessible than the superclass (e.g., Animal has public void doStuff() and Cat extends Animal has private void doStuff()
Static and non-static methods don't really affect inheritance either. Static variables work the same way, except relative to the class of interest
public class Magic{
public static int pants;
}
public class MagicPants extends Magic{
public void go(){
System.out.println(pants);
System.out.println(MagicPants.pants);
System.out.println(Magic.pants);
}
public static void main(String argv[]){
Magic.pants = 2;
MagicPants.pants = 1;
new MagicPants().go();
}
}
All print 1
Constructor code flow is easy - follow the super() calls.
So i don't know graphics.
Static means the variable is the same for all object which have the same class.
Like
public Class TryVariable{
public static int variable = 2
public static void main(String[] args){
a = new TryVariable()
b = new TryVariable()
system.out.println(a.variable)
system.out.println(b.variable)
// both equals 2
a.variable= 3
system.out.println(a.variable)
system.out.println(b.variable)
// both equals 3, because variable is static.
}
Public variable means you can directly change directly her by the way i do in ma previous example: object.variableName = value.
This is dangerous, all people inadvisable to use it.
Private variable can't be change directly you need to use somes getters and setters to do this work. It's is the good way to code.
The defaut, i'm not sur of all parameters so i don't describe to you. But 99.9% of time the private is use.
Protected mean, the variable is open to packages and sub classes (in first time private is easier to use and safer)
An other parameter can be final, with this parameter the variable can't be change any more. It's like a constant. And a static final parameter is a class constant.
If you need more information, previous response explain where are find the officials sources.
This is very easy example: http://vskl.blogspot.cz/2009/05/polymorphism-in-java.html
every time you create Circle or Square object, Shape object is created too
About the variables:
- private fields are not accessible by any other class including subclasses.
- protected fields are accessible by any subclass. Taken the picture from the link, variables x and y of abstract class Shape, every instance of Circle or Square have these fields.
- default fields are accessible by any subclass and by any class in the same package(only in same package, classes in subpackages do not have access). This is useful typicaly when writing automated test, you don't have to declare public getter for the field.
- public fields are accessible by any other class. However using those is not a clean way how to write code, it is better to create private field with getter and setter.
- static keyword designates field owned by class, not by it's instances. It is like having one field shared by multiple instances of the class. If one instance changes value of this field, every other instance can read only this new modified