Class and Inner class access modifier [duplicate] - java

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.

Related

Private member of a Static Nested Class in Java [duplicate]

This question already has answers here:
Why can outer Java classes access inner class private members?
(10 answers)
Closed 2 years ago.
Could someone please explain how private members of a static nested class are accessible outside the class?
class Main {
static class Inner{
private static int calc= 10;
}
public static void main(String args[]){
System.out.println("calc is "+Main.Inner.calc);
}
}
The inner class is just a way to cleanly separate some functionality that really belongs to the original outer class.
The inner class is (for purposes of access control) considered to be part of the containing class. This means full access to all privates.
The way this is implemented is using synthetic package-protected methods: The inner class will be compiled to a separate class in the same package. The JVM does not support this level of isolation directly, so that at the bytecode-level will have package-protected methods that the outer class uses to get to the private methods/fields.
If you like to hide the private members of your inner class, you may define an Interface with the public members and create an anonymous inner class that implements this interface.

Access levels of classes 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 5 years ago.
A class from a subpackage needs to access a class from a package one level up. So, I need to keep the target class as public. But I don't want that class to be accessed by any other class. What can I do?
You don't have dozen solutions.
Java is not C++ or OOP languages that have the concept of "friend class".
The protected modifier provides a privileged access for the subclasses but you will not subclass a dependency to access it.
It really makes no sense.
So if you can refactor : move the user class in the same package as the used class and use the private package modifier.
Otherwise, make the class a private nested class of a public factory class that will return a instance of a specific interface matching to the class API you want to protect the access.
In this way, the client classes will only communicate with the interface API.
Of course any class will still to be able to retrieve the instance but will never be coupled with an implementation class.
So in a some way, it protects the access to the class.
FooAPI :
public interface FooAPI {
void foo();
//....
}
FooFactory :
public class FooFactory{
private MyFactory(){
}
private class MyPrivateFoo implements FooAPI{
// implements the interface methods
#Overrided
public void foo(){
// ....
}
}
public FooAPI of(){
return new MyPrivateFoo();
}
}
Edit for your comment :
The used class has public methods which change its state. Only
specific classes are allowed to change its state, others are not. How
can this be solved ?
The question was not very clear about class access meaning.
With this comment, it is clear.
State changing is a functional behavior.
You want to protect the state change of an instance of a specific class ?
So make this class responsible to decide whether the state should change or not.
Don't provide public methods that allow to do it directly.
You have to change your design.
For example introduce a public doProcessing() method in the class with the state you want to control and make this method responsible to change the state instance if relevant.
You can be interested in Domain Model design that gives a natural and straight way to address this kind of issue.
And to ensure the validity of a behavior, you have a powerful tool : the unit and integration tests.
So use them.
Use protected modifier so the subclass and the package level classes can alone access it
PLease refer to the link for details on access levels
https://www.programcreek.com/2011/11/java-access-level-public-protected-private/
Refactor your code, depending on your concrete scenario:
Make the class in the subpackage inherit from the class a level up.
Create an interface in the subpackage that provides the methods you want to access and let the class in the package implement it.
Move one of the classes.
A class can not be private or protected. The only access modifiers of class is public or no-modifier. But you can use public, private, protected or no-modifier as inner class.
A class can access all properties of another class in same package except private modifier.
Keep all properties as protected in parent class. So, only child class from same or other package can access the parent class properties. Other class will not be able to access.

I can access a protected field outside of class 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 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.

Public constructor of a private class [duplicate]

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.

Why can't two public classes be defined in one file in java? [duplicate]

This question already has answers here:
Why is each public class in a separate file?
(11 answers)
Closed 9 years ago.
Why Class B can't become public?
How can I use class be in other classes? Is it better to define it inside Cons?!
// public class B { why not?
class B {
int x;
B (int n) {
x=n;
System.out.println("constructor 'B (int n)' called!");
}
}
public class Cons {
public static void main(String[] args) {B b = new B();}
}
As per java language specification, there can be only one public class in a file (.java) and file name should be same as public class name.
If you want class B accessible in other placs, you may create a separate B.java file and move your Class B code to that file.
This thread may give you some more information.
Q. Why can't two public classes be defined in one class scope in java?
A. Just the way the language is designed. Once you get used to it, you'll find it helps you organize your code.
Q. Why Class B can't become public?
A. It can, but it has to be in a file called B.java. And it has to be the only public class in that file.
Q. How can I use a class in other classes?
A. You might want to rephrase the question. But there are multiple approaches:
Make the class public, instantiate it, and call methods on it.
Add the class to the same file, don't make it public (you won't be able to), instantiate it, and call methods on it. You'll be able to use it from other classes in the same file or package. This is the "default" access modifier, and it means that you'll be able to instantiate this class from within other classes in the same package.
Make it an inner (or nested) class, instantiate it, and call methods on it. It will only be accessible by name from within its parent class. This is supposed to increase encapsulation and make code more readable. http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Q. Is it better to define it inside Cons?
A. I personally don't find myself doing that very often. I find it makes the code a bit messier, though the above links says otherwise.
Put your classes in different files.
The name of the class should match the name of the file.

Categories

Resources