理解 java 內部類
1、內部類基礎知識:
一般定義在java類內部的類成為內部類
內部類可以分為:定義在方法體外部的類、定義方法內部的類、靜態內部類(只能定義在方法外部),匿名內部類
說明:
定義在方法外面的類:
類的成員變量(靜態、非靜態)可以訪問,為了保證能夠正確的引用的類的成員變量,所以必須先實例化外部類的對象,才可以實例化內部類的對象
訪問權限可以任何,可以把它看成類的成員變量,這樣理解就好多來了。
定義在方法體內的類;
類的成員變量(靜態、非靜態)可以訪問,為了保證能夠正確的引用的類的成員變量,所以必須先實例化外部類的對象,才可以實例化內部類的對象
訪問權限不可以有,把他看成方法的局部變量就可以了。
靜態內部類:
只能訪問類的靜態成員變量
訪問權限任何
匿名內部類:
類的成員變量(靜態、非靜態)可以訪問,為了保證能夠正確的引用的類的成員變量,所以必須先實例化外部類的對象,才可以實例化內部類的對象
訪問權限不可以有
2、內部類的作用
內部類可以很好的隱藏類,一般類不允許有private protect default訪問權限。
內部類可以實現多重基礎,彌補了java不能多繼承的特點
3、例子
- package com.ajun.test.innerclass.example;
- /**
- * 水果內容
- * @author Administrator
- *
- */
- public interface Contents {
- String value();
- }
- package com.ajun.test.innerclass.example;
- /**
- * 水果目的地
- * @author Administrator
- *
- */
- public interface Destination {
- //目的地
- String readLabel();
- }
- package com.ajun.test.innerclass.example;
- public class Goods {
- private String des="is ruit!!";
- //方法外部
- private class Content implements Contents{
- private String name = "apple "+des;
- @Override
- public String value() {
- return name;
- }
- }
- //方法外部
- private class GDestination implements Destination{
- private String label ;
- private GDestination(String label){
- this.label= label;
- }
- @Override
- public String readLabel() {
- return label;
- }
- }
- //匿名內部類
- public Destination getdestination(final String label){
- return new Destination(){
- @Override
- public String readLabel() {
- return label;
- }
- };
- }
- public Destination dest(String s){
- return new GDestination(s);
- }
- public Contents content(){
- return new Content();
- }
- public Destination dest2(String s){
- class GDestination implements Destination{
- private String label;
- private GDestination(String label){
- this.label= label;
- }
- @Override
- public String readLabel() {
- return label;
- }
- }
- return new GDestination(s);
- }
- }
- package com.ajun.test.innerclass.example;
- public class Test {
- public static void main(String [] a){
- Goods gs = new Goods();
- Contents c = gs.content();
- Destination d = gs.dest("Beijing");
- System.out.println(c.value());
- System.out.println(d.readLabel());
- Destination d1 = gs.getdestination("Shanghai");
- System.out.println(d1.readLabel());
- System.out.println(gs.dest2("Tianjin").readLabel());
- }
- }
其中Content和Gdestination得到了很好的隱藏,外面調用的時候,根本就不知道調用的是具體哪個類,使這個類擁有多繼承的特性。
輸出;
- apple is ruit!!
- Beijing
- Shanghai
- Tianjin