public class Test {class A { }static class B { }public static void main(String[] args) {/*will fail - compilation error, you need an instance of Test to instantiate A*/A a = new A();/*will compile successfully, not instance of Test is needed to instantiate B */B b = new B();}}
public class TestMyStaticClass {public static void main(String []args){MyStaticClass.setMyStaticMember(5);System.out.println("Static value: " + MyStaticClass.getMyStaticMember());System.out.println("Value squared: " + MyStaticClass.squareMyStaticMember());// MyStaticClass x = new MyStaticClass(); // results in compile time error}}
// A top-level Java class mimicking static class behaviorpublic final class MyStaticClass {private MyStaticClass () { // private constructormyStaticMember = 1;}private static int myStaticMember;public static void setMyStaticMember(int val) {myStaticMember = val;}public static int getMyStaticMember() {return myStaticMember;}public static int squareMyStaticMember() {return myStaticMember * myStaticMember;}}
public class Outer {static class Nested_Demo {public void my_method() {System.out.println("This is my nested class");}}public static void main(String args[]) {Outer.Nested_Demo nested = new Outer.Nested_Demo();nested.my_method();}}
public class MyClass {// Static methodstatic void myStaticMethod() {System.out.println("Static methods can be called without creating objects");}
// Public methodpublic void myPublicMethod() {System.out.println("Public methods must be called by creating objects");}
// Main methodpublic static void main(String[ ] args) {myStaticMethod(); // Call the static method// myPublicMethod(); This would output an error
MyClass myObj = new MyClass(); // Create an object of MyClassmyObj.myPublicMethod(); // Call the public method}}
public final class ClassSingleton {
private static ClassSingleton INSTANCE;private String info = "Initial info class";
private ClassSingleton() {}
public static ClassSingleton getInstance() {if(INSTANCE == null) {INSTANCE = new ClassSingleton();}
return INSTANCE;}
// getters and setters
public String getInfo(){return info;}}