Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

Why are you not able to declare a class as static in Java?

1 Answer

0 votes
by (46k points)

Solely nested classes can be static. By performing so you can use the nested class without holding an instance of the outer class.

 

class OuterClass{

    public static class StaticNestedClass{

    }

 

    public class InnerClass{

    }

 

    public InnerClass getAnInnerClass(){

        return new InnerClass();

    }

 

    //This method doesn't work

    public static InnerClass getAnInnerClassStatically(){

        return new InnerClass();

    }

}

 

class OtherClass{

    //Use of a static nested class:

    private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();

    //Doesn't work

    private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();

    //Use of an inner class:

    private OuterClass outerclass= new OuterClass();

    private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();

    private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();

To learn more about nested classes click here.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...