Why can't the class be declared static?

Asked 2 years ago, Updated 2 years ago, 161 views

Why can't the class be declared static?

java static-class

2022-09-22 22:34

1 Answers

There's a static declaration. But it's only possible in overlapping classes. Declare it statically when you want to use it without an instance of an outside class in an external class

as shown in the example below
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();
}

Four overlapping classes It will be helpful to study.


2022-09-22 22:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.