Java中的静态类

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

null

如果没有外部类的实例,则无法创建内部类的实例。因此,内部类实例可以访问其外部类的所有成员,而无需使用对外部类实例的引用。因此,内部类可以帮助程序变得简单和简洁。

记得: 在静态类中,我们可以轻松创建对象。

静态和非静态嵌套类之间的差异

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

  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: GeeksForGeeksMessage from non-static nested class: GeeksForGeeksMessage from non-static nested class: GeeksForGeeks

本文由 钱德拉·普拉卡什 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享