why top level class could not be static

Answer Posted / 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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are inner classes or non static nested classes in java?

705


What is integer parseint?

546


Is static a keyword in java?

522


What is final method?

580


Is it possible to override private or static method in java?

542






Addition to previous section relative word 5th one was Putrid ans: rotten, also there was prob. in 1st section on bucket weight ans:10kg, also there was a prob. on train speed to find bridge length ans:800 mtrs.

1604


Is alive method in java?

505


How to sort an array in java without using sort method?

522


what are three ways in which a thread can enter the waiting state? : Java thread

570


What is difference between float and double?

500


What are the five major types of reference sources?

532


What is loop in java?

525


What is a double vs float?

535


Difference between start() and run() method of thread class?

586


What are the different tags provided in jstl?

549