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 do you mean by inner class in java? Explain

582


What is the difference between double and float variables in java?

630


What loop means?

553


What is linked hashset and its features?

541


what is deadlock? : Java thread

519






What is the purpose of java?

556


Can this keyword be used to refer static members?

540


What are the 4 types of research methods?

507


How do you end a program?

540


How hashset works internally in java?

581


Why is java so popular?

627


What are different data structures in java?

523


List implementations of list interface?

555


What is polymorphism and what are the types of it?

494


Can an object be null?

541