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.
Related
I have just found a static nested interface in our code-base.
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a Listener. If you had a class Foo and you wanted other classes to be able to listen for events on it, you could declare an interface named FooListener, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement Foo.Listener (a nested class Foo.Event isn't bad along with this).
Member interfaces are implicitly static. The static modifier in your example can be removed without changing the semantics of the code. See also the the Java Language Specification 8.5.1. Static Member Type Declarations
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with Foo.Bar, like so:
public class Baz implements Foo.Bar {
...
}
In most ways, this isn't different from a static inner class.
Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with any class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, an inner interface enables the construction of custom types and improves their encapsulation.
class ConcreteA implements A {
:
}
class ConcreteB implements B {
:
}
class ConcreteC implements C {
:
}
class Zoo implements A, C {
:
}
class DoSomethingAlready {
interface AC extends A, C { }
private final AC ac;
DoSomethingAlready(AC ac) {
this.ac = ac;
}
}
To answer your question very directly, look at Map.Entry.
Map.Entry
also this may be useful
Static Nested Inerfaces blog Entry
Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)
If you will change class Foo into interface Foo the "public" keyword in the above example will be also redundant as well because
interface defined inside another interface will implicitly public
static.
In 1998, Philip Wadler suggested a difference between static interfaces and non-static interfaces.
So far as I can see, the only difference in making an
interface non-static is that it can now include non-static inner
classes; so the change would not render invalid any existing Java
programs.
For example, he proposed a solution to the Expression Problem, which is the mismatch between expression as "how much can your language express" on the one hand and expression as "the terms you are trying to represent in your language" on the other hand.
An example of the difference between static and non-static nested interfaces can be seen in his sample code:
// This code does NOT compile
class LangF<This extends LangF<This>> {
interface Visitor<R> {
public R forNum(int n);
}
interface Exp {
// since Exp is non-static, it can refer to the type bound to This
public <R> R visit(This.Visitor<R> v);
}
}
His suggestion never made it in Java 1.5.0. Hence, all other answers are correct: there is no difference to static and non-static nested interfaces.
In Java, the static interface/class allows the interface/class to be used like a top-level class, that is, it can be declared by other classes. So, you can do:
class Bob
{
void FuncA ()
{
Foo.Bar foobar;
}
}
Without the static, the above would fail to compile. The advantage to this is that you don't need a new source file just to declare the interface. It also visually associates the interface Bar to the class Foo since you have to write Foo.Bar and implies that the Foo class does something with instances of Foo.Bar.
A description of class types in Java.
Static means that any class part of the package(project) can acces it without using a pointer. This can be usefull or hindering depending on the situation.
The perfect example of the usefullnes of "static" methods is the Math class. All methods in Math are static. This means you don't have to go out of your way, make a new instance, declare variables and store them in even more variables, you can just enter your data and get a result.
Static isn't always that usefull. If you're doing case-comparison for instance, you might want to store data in several different ways. You can't create three static methods with identical signatures. You need 3 different instances, non-static, and then you can and compare, caus if it's static, the data won't change along with the input.
Static methods are good for one-time returns and quick calculations or easy obtained data.
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.
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
How do I declare a static class in java? eclipse wants me to remove "static" from the declaration.
static public class Constants {
First to answer your question:
Only a Nested class can be declared static. A top level class cannot declared be static.
Secondly, Inner class is a nested class that is not explicitly declared static. See the java language spec. So contrary to some answers here, Inner classes cannot be static
To quote an example from the spec:
class HasStatic{
static int j = 100;
}
class Outer{
class Inner extends HasStatic{
static final int x = 3; // ok - compile-time constant
static int y = 4; // compile-time error, an inner class
}
static class NestedButNotInner{
static int z = 5; // ok, not an inner class
}
interface NeverInner{} // interfaces are never inner
}
If by 'static' you mean 'can have only static members', there's no such thing in Java.
Inner classes (and only them) can be static, but that's a different concept. Inner static classes can still have instance members.
Eclipse complains correctly, your code won't compile as Top level class can't be declared as static.
You need to first understand what static class means.
static class :
Top level class can't be declared as static. Only Member and Nested top-level classes can be defined as static.
You declare member classes when you want to use variables and methods of the containing class without explicit delegation. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared. If you want to remove this restriction, you declare the member class a static class.When you declare a member class with a static modifier, it becomes a nested top-level class and can be used as a normal top-level class as explained above.
nested top-level class is a member classes with a static modifier. A nested top-level class is just like any other top-level class except that it is declared within another class or interface. Nested top-level classes are typically used as a convenient way to group related classes without creating a new package.
Also check when should we go for static class,variables and methods in java
As you have already been told from the other comments, classes cannot be declared static. However there are alternatives to this problem.
The most simple one is to precede all member variables and methods with the static modifier. This essentially does what you want.
A slightly more involved alternative is to make the class a singleton. This is a class in which through the use of a private constructor, and an instanceOf() method, or just an Enum, you can only have one instance of that class. Semantically and syntactically you treat that instance as an ordinary instance of whatever particular class you are making a singleton, but you can only have a single instance of that class, which you retrieve via SomeObject.instanceOf(), or in an Enum implementation, SomeObject.INSTANCE.
You would normally use Enums to implement this, minus the edge cases where you are extending another class.
For more complete information on singletons visit the link below.
Design Patterns in Java - Singleton
There is no direct equivalent of C# static classes in Java, but the closest thing in my opinion is an empty enum, which might seem weird at first, but makes sense the more you think about it. An enum in Java (unlike in C#) is essentially a set of singleton instances that all implement the same abstract base class and interfaces. The quickest and safest way to make a normal singleton in Java is like so:
enum Foo {
INSTANCE;
public Bar doSomething(Baz baz) {
return Bar.fromBaz(baz); // yadda yadda
}
}
So since we are dealing with sets of singletons, it make sense that we can have an empty set. And an empty set means there can be no instances. This is conceptually the same as a static class in C#.
enum MyUtilities {
;
static Bar doSomething(Baz baz) {
return Bar.fromBaz(baz); // yadda yadda
}
static final String SOME_CONSTANT = "QUX";
}
This is great because you won't lose test coverage because of hard to test private constructors in a final class, and the code is cleaner than a final class with an empty private constructor.
Now, if the static classes are meant to all work on a single Interface and you have control of that Interface, then you should implement the static methods on that Interface itself (something you can't do in C#).
All top level classes are implicitly static, meaning they can be accessed by everybody. So it makes sense only to make inner classes optionally static.
Is it possible to have an inner class inside the interface in java ???
You can. But here's what O'Reilly says about it:
Nested Classes in Interfaces?
Java supports the concept of nested classes in interfaces. The syntax and dynamics work just like nested classes declared in a class. However, declaring a class nested inside an interface would be extremely bad programming. An interface is an abstraction of a concept, not an implementation of one. Therefore, implementation details should be left out of interfaces. Remember, just because you can cut off your hand with a saw doesn't mean that it's a particularly good idea.
That said, I could see an argument for a static utility class nested into an interface. Though why it would need to be nested into the interface instead of being a stand-alone class is completely subjective.
I agree that this should be generally rare, but I do like to use inner classes in interfaces for services when the interface method needs to return multiple pieces of information, as it's really part of the contract and not the implementation. For example:
public interface ComplexOperationService {
ComplexOperationResponse doComplexOperation( String param1, Object param2 );
public static class ComplexOperationResponse {
public int completionCode;
public String completionMessage;
public List<Object> data;
// Or use private members & getters if you like...
}
}
Obviously this could be done in a separate class as well, but to me it feels like I'm keeping the whole API defined by the interface in one spot, rather than spread out.
Yes, it is possible but it is not common practice.
interface Test
{
class Inner
{ }
}
class TestImpl implements Test
{
public static void main(String[] arg)
{
Inner inner = new Inner();
}
}
Doesn't answer your question directly, but on a related note you can also nest an interface inside another interface. This is acceptable, especially if you want to provide views. Java's collection classes do this, for example Map.java in the case of the Map.Entry view:
public interface Map<K,V> {
...
public static interface Entry<K,V> {
....
}
}
This is acceptable because you're not mixing implementation details into your interface. You're only specifying another contract.
Yes. Straight from the language spec:
An inner class is a nested class that is not explicitly or implicitly declared static.
And (boldface mine):
A nested class is any class whose declaration occurs within the body of another class or interface.
One use case for this that I find quite useful is if you have a builder that creates an instance of the Interface. If the builder is a static member of the Interface, you can create an instance like this:
DigitalObject o = new DigitalObject.Builder(content).title(name).build();
It is legal, but I only really do it with nested interfaces (as already mentioned) or nested enums. For example:
public interface MyInterface {
public enum Type { ONE, TWO, THREE }
public Type getType();
public enum Status { GOOD, BAD, UNKNOWN }
public Status getStatus();
}