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

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.

Related

Class and Inner class access modifier [duplicate]

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.

Static nested class instance [duplicate]

This question already has answers here:
Java inner class and static nested class
(28 answers)
Closed 7 years ago.
I came across this in java, I know its a static nested class but why create an instance of 'static'. Isn't the whole idea of 'static' to use it without an instance? I understand the concept of inner classes, but why (and frankly how is it possible to) create an 'instance' of a 'static' member at all ?
Why this:
1- OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
2- nestedObject.aNestedClassMethod();
and not this:
1- OuterClass outerInstance=new OuterClass();
2- outerInstance.StaticNestedClass.aNestedClassMethod();
Use on inner classes, the keyword static indicates that you can access the inner class without an instance of the outer class.
For example:
public class Outer {
public static class Inner {
/* Code here. */
}
}
with this construction, you can create an instance of the inner class by using this code:
new Outer.Inner()
If the inner class would not be static, but also like this:
public class Outer {
public class Inner {
/* Code here. */
}
}
Then, you would have to create an instance of Outer in order to access Inner:
new Outer().new Inner()
Don't think of a static class as being a member of its enclosing class. It's a class of its own, totally separate. The only real distinction between it and a top-level class is that it has a slightly different name, and it can be private — which again doesn't affect its semantics, other than the fact that only the enclosing class knows about it.
So, if I have:
public class EnclosingClass {
public static class InnerClass {
}
}
Then anyone can come around and do:
EnclosingClass.InnerClass instance = new EnclosingClass.InnerClass();
See: exactly the same as a top-level class.
This is actually true of an inner class, too. There things are slightly more complicated, but basically the idea is that the inner class is still its own class, but it has a (mostly hidden) reference to the instance of the enclosing class that created it. I say "mostly" because it's possible to access that instance, via EnclosingClass.this. The java compiler also does some convenience plumbing for you, such that someFieldInTheEnclosingClass becomes EnclosingClass.this.someFieldInTheEnclosingClass. But don't let that shorthand fool you: the inner class is its own separate class, and its instance is its own separate instance; they're no different than a top-level class in that regard.
Thanks everyone who replied and commented. I have finally got the hang of it. I guess the answer was right in front of my eyes.
The reason behind calling a an inner static class 'static' is how its referenced and not how the class behaves. Since we don't need and instance of the OuterClass to create an instance of InnerClass and we simply use OuterClass name, rather than its object to instantiate the inner class.
Special thanks to Sleiman Jneidi, who posted the very first comment, the name static here "is" misleading.
1- OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

private abstract classes in Java [duplicate]

This question already has answers here:
Why nested abstract class in java
(2 answers)
Closed 8 years ago.
I am a relative newcomer to Java. I recently came across a private static abstract class inside a regular class while browsing some Android app source code. What could be a use case for such a nested class? How would it be used and what sort of design benefits are there from using such a class?
I've never come across this pattern before myself, but I can imagine it being useful if:
You want to implement an interface in a similar way in a bunch of nested classes (e.g. to be returned from public methods within the enclosing class)
Those interface implementations have a lot of code in common (hence the abstract class)
You don't need any code other than the implementations to know about the abstract class
The subclasses of the abstract class may well be private as well. (Typically when I write nested classes, they're private implementation details.) For example:
public interface Foo {
// Methods here
}
public class FooFactory {
public static Foo getFoo1() {
return new Foo1();
}
public static Foo getFoo2() {
return new Foo2();
}
private static abstract class AbstractFoo implements Foo {
// Implement methods in Foo in terms of
// doSomething()...
// Implementation-specific method
public abstract void doSomething();
}
private static class Foo1 extends AbstractFoo {
public void doSomething() {
}
}
private static class Foo2 extends AbstractFoo {
public void doSomething() {
}
}
}
What could be a use case for such a nested class?
You would use this if:
you were going to implement a number of nested classes with common functionality, and
you didn't want the base class with that functionality to be visible.
You would probably also make the leaf classes either final or private.
How would it be used and what sort of design benefits are there from using such a class?
See above. Basically, you are hiding the class so that it cannot be directly subclassed outside of the outermost enclosing class. I think this will also prevent the subclasses from being used polymorphically outside of the outermost enclosing class.
This is not a common use-case, but I imagine it is sensible in the context that you found it.
A typical use is to replace the equivalent of a C struct - for instance a small class that contains a name and a value and gets stored in a List or Map in the enclosing class. Because it is not used outside of the compilation unit, it can be private.
The static keyword usage is a bit odd here; all it means is that the class has no connection with the enclosing class.
Making it abstract is unusual - it indicates that there will be concrete implementations and I have never done that. YMMV...
The purpose of a nested class is to clearly group the nested class with its surrounding class, signaling that these two classes are to be used together.
Nested classes are considered members of their enclosing class. Thus, a nested class can be declared public, package (no access modifier), protected and private (see access modifiers for more info).
Static Nested Classes
Static nested classes are declared like this:
public class Outer {
public static class Nested {
}
}
In order to create an instance of Nested you must reference it by prefixing it with the Outer class name, like this:
Outer.Nested instance = new Outer.Nested();
A static nested class is essentially a normal class that has just been nested inside another class. It interacts with its enclosing class in the same way. Being static, a static nested class can only access instance variables of the enclosing class via a reference to an instance of the enclosing class.

Static classes and final classes in java [duplicate]

This question already has answers here:
What is the point of "final class" in Java?
(24 answers)
Closed 9 years ago.
In Java (and in Android), what's the use of static class and final class declarations?
My question is not about static instances but class declarations like,
static class StaticClass {
//variables and methods
}
and
final class FinalClass {
//variables and methods
}
Thanks,
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Final Classes
A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
http://docs.oracle.com/javase/tutorial/java/IandI/final.html
final classes will restrict for further extends (Inherit).
You can not use static keyword on outer class,static is permitted only to inner classes Static classes
You make a class final so it can not be extended. Usually it makes sense if you'are creating a library (or working on a part of a big project), so your clients are not able to extend the class and modify the existing behavior. In your own program there's little reason to make a class final unless it's a big program and you can inadvertently forget things.
Static inner classes are for things that logically belongs to an outer (containing) class but which have no dependencies on the state of the outer class. For example you can have a Parser class and an inner Parser.Listener class. Normally if you decide to have an inner class try, first, to make it static, if possible, to simplify things.
You could do without both final and static inner classes then with experience you will find use for them.
other class can not extends the final class exmple String is final class so you cannot extends this class.
You cannot have a 'top-level' class declared static. You can only have an inner class with the modifier 'static'.
static inner class only access the static member of the outer class
if you make a class as final then it can not be inherited. Generally top level class can not be made static however inner class can be made as static and Nested static class doesn’t need reference of Outer class
static and final class in java
you can't mark a class static ?
yes, if it is nested class
no, if it is normal class.
if you mark a nested class static it will work as fully flagged class just use a classname.staticClassNmae to access it.
if you mark a class final , it can't be inherited , a good example of this String class in java.

When would I want to make my private class static?

In general, are there any benefits in declaring a private class as static?
In what cases would I want to use one of the following over the other?
private static class Foo
{
...
}
vs
private class Foo
{
...
}
I think this is a good starting point:
http://java67.blogspot.fi/2012/10/nested-class-java-static-vs-non-static-inner.html
1) Nested static class doesn't need reference of Outer class but non
static nested class or Inner class requires Outer class reference. You
can not create instance of Inner class without creating instance of
Outer class. This is by far most important thing to consider while
making a nested class static or non static.
2) static class is actually static member of class and can be used in
static context e.g. static method or static block of Outer class.
3) Another difference between static and non static nested class is
that you can not access non static members e.g. method and field into
nested static class directly. If you do you will get error like "non
static member can not be used in static context". While Inner class
can access both static and non static member of Outer class.
If i understand correctly, the question is for private class vs private static class. All the responses are generally about inner classes, that are not 100% applied to that question. So first things first:
From geeksforgeeks:
Nested class -> a class within another class
static nested class -> Nested classes that are declared static are called static nested classes
inner class -> An inner class is a non-static nested class.
As the accepted response says, static vs non-static nested classes differ on the way and possibility to access methods/fields outside the outer class. But in case of private classes B within class A, you dont have this issue, cause B is not accessible outside A anyway.
Now, from inside class A, for non-static fields/methods you can always refer to class B, either by saying new A.B() or just new B() and it doesnt matter (no compilation/runtime errors) if B is private class or private static class. In case of static fields/methods you need to use a private static class.
Moreover, if you want to access from inside B a non-static field of A, then you can't have B as private static class.
I generally prefer private static class, except when i cant use it like in the previous case, cause intellij will give warnings otherwise.
If you need access to the member variables/methods of the enclosing class, use the non-static form. If you don't, use the static form.
I would assume you are referring to inner classes.
I think the motivation would be coming from how you want to associate your inner class. If you want your inner class to be associated to a specific instance of its outer class, you'd use private class, otherwise, use private static class.
I found it useful in having a specific exception in a generic abstract class. I.e.:
public abstract class AbstractClass <T>
{
private void doSomethingOrThrowException() throws SpecificException
{
....
if ( ! successful)
{
throw new SpecificException();
}
}
private static class SpecificException extends Exception {}
}
If I were to leave out the static, the compiler would give me an error that states: The generic class AbstractClass<T>.SpecificException may not subclass java.lang.Throwable
static classes differ from ordinary classes only in that they can be accessed without their instances being created. so if you need some class to be accessable every time, use static

Categories

Resources