Java內部類

來源:互聯網
上載者:User

標籤:abstract   情況   out   ref   com   ima   log   cst   技術   

以下內容為Google翻譯自https://www.tutorialspoint.com/java/java_innerclasses.htm:

在Java中,就像方法一樣,類的變數也可以有另一個類作為其成員。在Java中允許在一個類中編寫另一個類。寫入的類稱為內部,並且儲存內部類的類稱為外部類

文法:

以下是編寫嵌套類的文法。在這裡,類Outer_Demo是外部類,Inner_Demo類是內部類。

class Outer_Demo {   class Nested_Demo {   }}

內部類分為兩類:

  • 非靜態內部類 - 這是的非靜態成員。
  • 靜態內部類 - 這是的靜態成員。

一、內部類(非靜態內部類)

內部類是Java中的安全機制。一個類不能與存取修飾詞private關聯,但是如果將類作為其他類的成員,那麼內部類可以被設為私人的。這也用於訪問類的私人成員。

內部類有三種類型,具體取決於它們的定義和位置。他們是:

  • 內部類
  • 方法本地內部類
  • 匿名內部類

1、內部類

建立一個內部類是非常簡單的。只需要在類中寫一個類。與類不同,內部類可以是私人的,一旦聲明一個內部類是私人的,就不能從類之外的對象訪問它。

以下是建立內部類並訪問它的程式。在給定的例子中,使內部類是私人的,並通過一種方法訪問類。

樣本:

class Outer_Demo {   int num;      // inner class   private class Inner_Demo {      public void print() {         System.out.println("This is an inner class");      }   }      // Accessing he inner class from the method within   void display_Inner() {      Inner_Demo inner = new Inner_Demo();      inner.print();   }}   public class My_class {   public static void main(String args[]) {      // Instantiating the outer class       Outer_Demo outer = new Outer_Demo();            // Accessing the display_Inner() method.      outer.display_Inner();   }}

在這裡可以看到,Outer_Demo是外部類,Inner_Demo是內部類,display_Inner()是正在執行個體化內部類的方法,並且從main方法調用此方法。

如果編譯並執行上述程式,您將獲得以下結果:

This is an inner class.

訪問私人會員:

如前所述,內部類也用於訪問類的私人成員。假設一個類有私人成員訪問它們。在其中編寫一個內部類,從內部類的方法返回私人成員,例如getValue(),最後從另一個類(要從中訪問私人成員)調用內部類的getValue()方法類。

要執行個體化內部類,最初必須執行個體化外部類。此後,使用外部類的對象,以下是執行個體化內部類的方式。

Outer_Demo outer = new Outer_Demo();Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();

以下程式顯示如何使用內部類訪問類的私人成員。

樣本:

class Outer_Demo {   // private variable of the outer class   private int num = 175;        // inner class   public class Inner_Demo {      public int getNum() {         System.out.println("This is the getnum method of the inner class");         return num;      }   }}public class My_class2 {   public static void main(String args[]) {      // Instantiating the outer class      Outer_Demo outer = new Outer_Demo();            // Instantiating the inner class      Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();      System.out.println(inner.getNum());   }}

如果編譯並執行上述程式,將獲得以下結果:

The value of num in the class 
175

2、方法本地內部類

在Java中,可以在方法中編寫一個類,這將是本地類。像局部變數一樣,內部類的範圍在方法內受到限制。

方法局部內部類只能在定義內部類的方法中執行個體化。以下程式顯示如何使用方法本地內部類。

樣本:


public class Outerclass {   // instance method of the outer class    void my_Method() {      final int num = 23;      // method-local inner class      class MethodInner_Demo {         public void print() {            System.out.println("This is method inner class "+num);                }         } // end of inner class             // Accessing the inner class      MethodInner_Demo inner = new MethodInner_Demo();      inner.print();   }      public static void main(String args[]) {      Outerclass outer = new Outerclass();      outer.my_Method();                 }} 

如果編譯並執行上述程式,將獲得以下結果:

This is method inner class 23 

3、匿名內部類

被聲明為沒有類名的內部類被稱為匿名內部類。在匿名內部類的情況下,同時聲明和執行個體化它們。通常,當需要覆蓋類或介面的方法時,它們將被使用。匿名內部類的文法如下:

文法:

AnonymousInner an_inner = new AnonymousInner() {   public void my_method() {      ........      ........   }   };

以下程式顯示如何使用匿名內部類覆蓋類的方法。

樣本:

abstract class AnonymousInner {   public abstract void mymethod();}public class Outer_class {   public static void main(String args[]) {      AnonymousInner inner = new AnonymousInner() {         public void mymethod() {            System.out.println("This is an example of anonymous inner class");         }      };      inner.mymethod();       }}

如果編譯並執行上述程式,將獲得以下結果:

This is an example of anonymous inner class

以同樣的方式,可以覆蓋具體類的方法以及使用匿名內部類的介面。

匿名內部類作為論證:

一般來說,如果方法接受介面的對象,抽象類別或具體類,那麼可以實現介面,擴充抽象類別,並將對象傳遞給方法。如果是一個類,那麼可以直接將它傳遞給該方法。

但是在所有這三種情況下,可以將匿名內部類傳遞給該方法。這是傳遞一個匿名內部類作為方法參數的文法:

obj.my_Method(new My_Class() {   public void Do() {      .....      .....   }});

以下程式顯示如何傳遞匿名內部類作為方法參數。

樣本:

// interfaceinterface Message {   String greet();}public class My_class {   // method which accepts the object of interface Message   public void displayMessage(Message m) {      System.out.println(m.greet() +         ", This is an example of anonymous inner class as an argument");     }   public static void main(String args[]) {      // Instantiating the class      My_class obj = new My_class();      // Passing an anonymous inner class as an argument      obj.displayMessage(new Message() {         public String greet() {            return "Hello";         }      });   }}

如果編譯並執行上面的程式,它會是以下結果:

Hello This is an example of anonymous inner class as an argument

4、靜態內部類

靜態內部類是一個嵌套類,它是外部類的靜態成員。可以使用其他靜態成員訪問外部類。就像靜態成員一樣,靜態嵌套類無法訪問外部類的執行個體變數和方法。靜態嵌套類的文法如下:

文法:

class MyOuter {   static class Nested_Demo {   }}

執行個體化靜態嵌套類與執行個體化內部類有一點不同。以下程式顯示如何使用靜態嵌套類。

樣本:

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();   }}

如果編譯並執行上述程式,將獲得以下結果:

This is my nested class

 

測試工程:https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test16

Java內部類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.