Can a top-level class or interface have the "static" modifier? - java

Can a top-level class or interface be declared as static?
Example:
// File A.java
static Class A
{
...
}

No. static only applies to nested classes and tells that instances of the nested class do not need an instance of the surrounding class to be instantiated. As such, it makes no sense as applied to top classes.

Nope, top-level classes cannot be declared static; see JLS Section 8.1.1.
Not all modifiers are applicable to all kinds of class declarations ... The access modifier static pertains only to member classes ...

In java a top level class can't be defined as static.
read this

basically, you can make a static inner class but not top level class(outer one)
I think this post get a better explanation.
http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html
hopefully, it helps

All top level classes by default are static.
For those too hooked up about definition of statics and compiler errors.
A class itself is an object with application scope. So it's implicitly static.

Related

Java class which all its methods are static

What are the classes in Java which:
all its methods are static
Does not contain any instance methods
Lombok define it as UtilityClass:
A utility class is a class that is just a namespace for functions. No instances of it can exist, and all its members are static. For example, java.lang.Math and java.util.Collections are well known utility classes. This annotation automatically turns the annotated class into one.
A utility class cannot be instantiated. By marking your class with #UtilityClass, lombok will automatically generate a private constructor that throws an exception, flags as error any explicit constructors you add, and marks the class final. If the class is an inner class, the class is also marked static.
All members of a utility class are automatically marked as static. Even fields and inner classes.
It sounds like you're describing a static class.
While Java does not allow you to explicitly declare a (non-nested) class as static, it is still possible to implement this paradigm.

Child Class cannot be protected

import java.util.*;
public class NewTreeSet2{
void count(){
for (int x=0; x<7; x++,x++){
System.out.print(" " + x);
}
}
}
protected class NewTreeSet extends NewTreeSet2{
public static void main(String [] args){
NewTreeSet2 t = new NewTreeSet2();
t.count();
}
}
Here, I cannot make the NewTreeSet sub class as protected. Why is this? I am not trying to accomplish anything, this is only for my understanding of the access specifiers.
public is the only access-modifier that can explicitly be applied to a top level class in Java. The protected modifier in case of a class can only be applied to inner classes.
Section 8.1.1 of the Java language specification says this :
The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration
So why can't top level classes be marked as protected? The purpose of protected access modifier in Java is to add restrictions on the access to a member of a class. Since a top level class is not a member of any class, the protected access modifier does not make sense for top level classes. Inner classes can be marked as protected because they are indeed members of a class. The same rules apply for private as well.
A class definition itself can only be public or package-private. Public classes must be defined in their own file and the filename must be the class name.
The documentation doesn't say anything about why there are only two access modifiers for the top level, but one might say that it is logical:
The protected access modifier makes sure only instances of the same or a child class can access the subject. Polymorphism is not applicable to classes, only to instances of classes. Thus the protected keyword there doesn't make sense.
If you want to protect the construction of objects, you should specify an access modifier to your constructor.
"Why can't we have the 'protected' modifier for a top-level class".
Assume it's allowed to use protected modifier for a class. Then what will happen, it will be visible to all the classes in the same package which is the same behavior what a default (package-level) access class will possess. Additionally this 'protected' class should be visible to all the subclasses outside package also. But unfortunately you would not be able to create any subclass of this class outside the package because this class itself will not be visible outside the package. Hence without the subclass specific behavior, this 'protected' class will be exactly same as a package-level or default access class. So, there is absolutely no need of 'protected' modifier for classes and hence, not permissible as well.
---This was posted in a different forum, by B Verma, found this answer according to which all of you said. It was really helpful, thank you.
http://www.coderanch.com/t/585021/java/java/Protected-access-modifier-class-level

Why private, static, protected access modifers are not used with a class?

and why the same, can be used with inner classes?
public class Hello {
class inner{ // this class can use any modifier
}
}
Java only allows top level classes / interfaces to be public or package.
Section 7.6 of the JLS states (Top Level Type Declarations):
By default, the top level types declared in a package are accessible
only within the compilation units of that package, but a type may be
declared to be public to grant access to the type from code in other
packages (§6.6, §8.1.1, §9.1.1).
Section 9.1.1 of the JLS of interface modifiers states:
The access modifiers protected and private pertain only to member
interfaces within a directly enclosing class or enum declaration
(§8.5.1).
The modifier static pertains only to member interfaces (§8.5.1, §9.5),
not to top level interfaces (§7.6).
I hope this is clear.
Nested classes can be static, private, protected, package-local, or public
Top level classes are not;
static as this wouldn't mean anything. static for a nest class means it doesn't hold a reference to an outer class, but if you are the outer class it doesn't have a use.
private classes cannot be access from another class file, so a private top level class couldn't be accessed.
protected classes could potentially be used from sub classes, but making the class abstract is clearer. IMHO.
Private top-level class does not make any sense because you can't access it from anywhere.
Protected means to access class within the same package or subclass of the outer class.Since there isn't package inheritance in java then protected classes also does not make any sense.
When we declare method/parameter as static, then we can access it without creating an instance of object.Because static member belongs to the class as a whole, not the instance of class or object. Since there isn't enclosing class for top-level classes, it is meaningless to define top-level classes as static.
All types of access modifiers can be used on all types of classs (except anonymous classes).
Classes with other types of modifiers, will give access, exactly like a method.
static won't work, since it means that it belongs to some other class, that is never true for an outer class.

Can outer class be defined as static and enclose inner static class?

It correct to define an outer class as static which have inside also a static class? Only one instance of outer and inner classes is needed. Can outer class be abstract and it's enclosed class be static?
No, a top level class can't be static. The meaning of "static" in a class declaration is only relevant to nested classes. You can certainly have a static nested class within an abstract class though.
From the JLS section 8.1.1:
The modifier static pertains only to member classes (§8.5.1), not to top level or local or anonymous classes.
Note that if you want "only one instance" of a class, you should potentially make it a singleton - which is entirely separate, and not something which affects the class declaration itself.

static class in java

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.

Categories

Resources