發文前,說下寫這個的緣故,本來以為自己對java內部類了解,其實是我太過于不覺得、以為不重要!所以,今天在重新寫下Demo,為自己記錄一下、回顧一下,
開始~~~
重新理解什么是內部類以及寫法、定義等;
代碼一:
1 package com.yk.nbn; 2 /** 3 * @author yk 4 * Date : 2020-06-22 5 * Nbn : 內部類 例子 6 */ 7 public class Nbn { 8 // 成員變數 name 9 private String name; 10 11 class Student1 { 12 private int age; 13 private String name; 14 15 // 有參構造器 16 public Student1(int age, String name) { 17 super(); 18 this.age = age; 19 this.name = name; 20 } 21 } 22 } 23 24 class Student2 { 25 int age; 26 String name; 27 28 // 構造器 29 public Student2(int age, String name) { 30 super(); 31 this.age = age; 32 this.name = name; 33 } 34 }
代碼一總結:
一、類名 Nbn中,Student1是內部類,Student2不是內部類,他們有區別,
二、類名 Nbn中,new物件的方式不一樣,
Student1 stu1 = new Nbn().new Student1(22, "劉備") ;
Student2 stu2 = new Student2(33, "陸遜");
代碼二 :
1 package com.yk.nbn; 2 3 import com.yk.nbn.Nbn.Student1; 4 5 /**\ 6 * @author yk 7 * 2020年6月22日 8 * 目的 : 在同一個包下,創建物件student 9 */ 10 public class Test01 { 11 12 public static void main(String[] args) { 13 Student1 stu1 = new Nbn().new Student1(22, "劉備") ; 14 Student2 stu2 = new Student2(33, "陸遜"); 15 Student3 stu3 = new Student3(44, "馬超"); 17 } 19 }
代碼二總結:
一、new物件Student的寫法,要注意,
圖:類的結構,在同一個包名下面

View Code
| 總結 |
|
一、Student1是內部類,Student2不是, 二、雖然Student2不是,但寫法不同,與類Student3相似,相似點:new物件寫法相同, 三、new物件Student1時,需要先new物件 Nbn(類名),然后像呼叫方法那樣 .new Student1() 的方式創建物件 |
用我自己的方式,每天記錄一點點,,,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/157146.html
標籤:Java
上一篇:出現這個 Incompatible types: 'PAnsiChar' and 'PWideChar' 編譯錯誤該如何處理?
下一篇:HTTP–Response詳解
