搜索
写经验 领红包
 > 财经

java中嵌套类用法介绍怎么写(java中嵌套类用法介绍怎么做)

导语:Java中嵌套类用法介绍

java中嵌套类用法介绍怎么写(java中嵌套类用法介绍怎么做)

在Java中,可以在另一个类中定义一个类。这些类称为嵌套类。它们使您能够对只在一个地方使用的类进行逻辑分组。因此,这增加了封装的使用,并创建了更具可读性和可维护性的代码。

嵌套类的作用域由其封闭类的作用域限定。因此,在上面的例子中,类NestedClass并不独立于类的 OuterClass外部类而存在。

嵌套类可以访问嵌套类的成员,包括私有成员。然而,反之则不然,即封闭类不能访问嵌套类的成员。

嵌套类也是其封闭类的成员。

作为其封闭类的成员,嵌套类可以声明为 private, public, protected, or package private (default)(私有、公共、受保护或包私有(默认))。

嵌套类分为两类:

1、静态嵌套类(static nested class):声明为静态的嵌套类称为静态嵌套类。

2、内部类(inner class):内部类是非静态嵌套类。

Syntax

class OuterClass{... class NestedClass { ... }}

Static Nested Classes(静态嵌套类)

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();// Java program to demonstrate accessing// a static nested class// outer classclass OuterClass{ // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private static int outer_private = 30; // static nested class static class StaticNestedClass { void display() { // can access static member of outer class System.out.println("outer_x = " + outer_x); // can access display private static member of outer class System.out.println("outer_private = " + outer_private); // The following statement will give compilation error // as static nested class cannot directly access non-static membera // System.out.println("outer_y = " + outer_y); } }}// Driver classpublic class StaticNestedClassDemo{ public static void main(String[] args) { // accessing a static nested class OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); nestedObject.display(); }}

Output:

outer_x = 10outer_private = 30

Inner Classes(内部类)

要实例化内部类,必须首先实例化外部类。然后,使用以下语法在外部对象中创建内部对象:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

There are two special kinds of inner classes :

// Java program to demonstrate accessing// a inner class// outer classclass OuterClass{ // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private int outer_private = 30; // inner class class InnerClass { void display() { // can access static member of outer class System.out.println("outer_x = " + outer_x); // can also access non-static member of outer class System.out.println("outer_y = " + outer_y); // can also access private member of outer class System.out.println("outer_private = " + outer_private); } }}// Driver classpublic class InnerClassDemo{ public static void main(String[] args) { // accessing an inner class OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new InnerClass(); innerObject.display(); }}

Output:

outer_x = 10outer_y = 20outer_private = 30

静态类和内部类(非静态嵌套类)的区别:

静态嵌套类不能直接访问封闭类的其他成员(非静态变量和方法),因为由于它是静态的,它必须通过对象访问封闭类的非静态成员。也就是说,它不能直接引用其封闭类的非静态成员。由于这个限制,静态嵌套类很少被使用。

非静态嵌套类(内部类)可以访问其外部类的所有成员(静态和非静态变量和方法,包括private),并且可以像外部类的其他非静态成员那样直接引用它们。

本文内容由小葵整理编辑!