why top level class could not be static
Answers were Sorted based on User's Feedback
Answer / vatsal doshi
The answer is in the question itself.
What is static? Something which belongs to a class and not its objects.
So if in a class, we have some variables, having single copy, we call them static.
Similarly some methods may be actually manipulating these static variables, so those methods are also static.
However, the class itself is static only if it belongs to some class(Definition of static)
So, for a class to be static, it must be a nested class. Such nested classes are called as Top Level Nested Classes in Java.
| Is This Answer Correct ? | 7 Yes | 1 No |
Answer / sanket mehta
static keyword is meant for providing memory and executing logic without creating Objects, a class does not have a value logic directly, so the static keyword is not allowed for outer class
If you declare the outer class as static, it will not allow to compile giving : Illegal modifier for the class classname; only public, abstract & final are permitted
| Is This Answer Correct ? | 0 Yes | 0 No |
Answer / sathishkumarbabu
All top-level classes are, by definition, static.
What the static boils down to is that an instance of the class can stand on its own. Or, the other way around: a non-static inner class (= instance inner class) cannot exist without an instance of the outer class. Since a top-level class does not have an outer class, it can't be anything but static.
Because all top-level classes are static, having the static keyword in a top-level class definition is pointless.
Some code to play around with:
public class Foo {
public class Bar {
// Non-static innner class
}
public static class Baz {
// Static inner class
}
}
public class Example {
public static void main(String[] args) {
new Foo(); // this is ok
new Foo.Baz(); // this is ok
new Foo.Bar(); // does not compile!
Foo f = new Foo();
Foo.Bar bar = f.new Bar(); //this works, but don't do this
}
}
I put the "but don't do this" in there because it's really ugly code design. Instance inner classes should not be visible outside the outer class. They should only be used from within the outer class.
Regards : Barend Garvelink
| Is This Answer Correct ? | 3 Yes | 4 No |
describe method overloading
Can an object?s finalize() method be invoked while it is reachable?
What are the differences between wait() and sleep()?
how you will prevent method overriding?
What is the difference between the reader/writer class hierarchy and the inputstream/outputstream class hierarchy in java programming?
Difference between throw and throws?
What are the legal operands of the instanceof operator?
When we can access the static data member without creating the object what is the need of the object in java.
5 Answers Airhub, ssinformatics,
Is list thread safe in java?
What is protected in java?
What are selection structures?
long d =10;int i =0;i=d; /// is this possible? If d is very long number (10 digits or some thing) then?