java静态类_Java静态类

  • Post author:
  • Post category:java


java静态类

Today we will look into java static class. It’s a good interview question to test your knowledge about nested classes in java.

今天,我们将研究java静态类。 测试您对Java嵌套类的了解是一个很好的面试问题。

Java doesn’t allow top level static classes, for example if we try to make a class static like below.

Java不允许顶层静态类,例如,如果我们尝试使类像下面这样静态化,则是不允许的。


Test.java


Test.java

static class Test {

}

We get following compilation error.

我们得到以下编译错误。

$ javac Test.java 
Test.java:1: error: modifier static not allowed here
static class Test {
       ^
1 error

Java静态类

(


Java static class


)

So is it possible to have static class in java?

那么有可能在Java中有静态类吗?

Yes, java supports nested classes and they can be static. These static classes are also called static nested classes.

是的,java支持嵌套类,它们可以是静态的。 这些静态类也称为静态嵌套类。

Java static nested class can access only static members of the outer class. Static nested class behaves similar to top-level class and is nested for only packaging convenience.

Java静态嵌套类只能访问外部类的静态成员。 静态嵌套类的行为类似于顶级类,并且仅出于包装方便而嵌套。

An instance of static nested class can be created like below.

静态嵌套类的实例可以如下创建。

OuterClass.StaticNestedClass nestedObj =
     new OuterClass.StaticNestedClass();

Java静态类示例

(


Java static class example


)

Let’s look at the example of java static class and see how we can use it in java program.

让我们看一下Java静态类的示例,看看如何在Java程序中使用它。

package com.journaldev.java.examples;

public class OuterClass {

	private static String name = "OuterClass";

	// static nested class
	static class StaticNestedClass {
		private int a;

		public int getA() {
			return this.a;
		}

		public String getName() {
			return name;
		}
	}
}

Now let’s see how to instantiate and use static nested class.

现在让我们看看如何实例化和使用静态嵌套类。

package com.journaldev.java.examples;

public class StaticNestedClassTest {

	public static void main(String[] args) {
		
		//creating instance of static nested class
		OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
		
		//accessing outer class static member
		System.out.println(nested.getName()); 
	}

}

Java静态类文件

(


Java static class file


)

Java static class file is named as

OuterClass$StaticClass.class

. Below image shows this for our example program.

Java静态类文件名为

OuterClass$StaticClass.class

。 下图显示了我们的示例程序。

Java静态类的好处

(


Java static class benefits


)

The only benefit I could think of is encapsulation. If the static nested class works only with the outer class then we can keep nested class as static to keep them close.

我唯一想到的好处就是封装。 如果静态嵌套类仅与外部类一起使用,那么我们可以将嵌套类保持为静态,以使它们保持紧密状态。

翻译自:

https://www.journaldev.com/12528/java-static-class

java静态类