📜  Java中的静态类

📅  最后修改于: 2022-05-13 01:54:40.762000             🧑  作者: Mango

Java中的静态类

Java允许在另一个类中定义一个类。这些被称为嵌套类。大多数开发人员都知道类可以是静态的,因此一些类可以在Java中设为静态。 Java支持静态实例变量、静态方法、静态块和静态类。定义嵌套类的类称为外部类。与顶级类不同,内部类可以是静态的。非静态嵌套类也称为内部类

如果没有外部类的实例,就无法创建内部类的实例。因此,内部类实例可以访问其外部类的所有成员,而无需使用对外部类实例的引用。出于这个原因,内部类可以帮助使程序简单明了。

静态和非静态嵌套类的区别

以下是静态嵌套类和内部类之间的主要区别。

  1. 静态嵌套类可以在不实例化其外部类的情况下进行实例化。
  2. 内部类可以访问外部类的静态和非静态成员。静态类只能访问外部类的静态成员。

例子

Java
// Java program to Demonstrate How to
// Implement Static and Non-static Classes
 
// Class 1
// Helper class
class OuterClass {
 
    // Input string
    private static String msg = "GeeksForGeeks";
 
    // Static nested class
    public static class NestedStaticClass {
 
        // Only static members of Outer class
        // is directly accessible in nested
        // static class
        public void printMessage()
        {
 
            // Try making 'message' a non-static
            // variable, there will be compiler error
            System.out.println(
                "Message from nested static class: " + msg);
        }
    }
 
    // Non-static nested class -
    // also called Inner class
    public class InnerClass {
 
        // Both static and non-static members
        // of Outer class are accessible in
        // this Inner class
        public void display()
        {
 
            // Print statement whenever this method is
            // called
            System.out.println(
                "Message from non-static nested class: "
                + msg);
        }
    }
}
 
// Class 2
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Creating instance of nested Static class
        // inside main() method
        OuterClass.NestedStaticClass printer
            = new OuterClass.NestedStaticClass();
 
        // Calling non-static method of nested
        // static class
        printer.printMessage();
 
        // Note: In order to create instance of Inner class
        //  we need an Outer class instance
 
        // Creating Outer class instance for creating
        // non-static nested class
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner
            = outer.new InnerClass();
 
        // Calling non-static method of Inner class
        inner.display();
 
        // We can also combine above steps in one
        // step to create instance of Inner class
        OuterClass.InnerClass innerObject
            = new OuterClass().new InnerClass();
 
        // Similarly calling inner class defined method
        innerObject.display();
    }
}


输出
Message from nested static class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks