zoukankan      html  css  js  c++  java
  • 内部类三:嵌套类

    嵌套类定义

    如果一个内部类生命为static,这种静态内部类称为嵌套类,嵌套类的对象不需要持有外围类的对象的引用。

    1) 要创建嵌套类的对象,并不需要器外围类的对象

    2)不能从嵌套类的对象中访问非静态的外围类对象,因为嵌套类的对象没有指向外围类对象的引用,因此无法访问外围类对象。

    嵌套类与普通内部类还有一个区别,普通内部类的字段与方法,只能放在类的外部层次上,所以普通内部类不能有static数据和static字段,也不能有嵌套类。

    但是嵌套类都可以包含这写内容

    package chapter10;
    
    public class Parcel11 {
        
        private String hello="hello world";
        
        private static String name="zhangsan";
        
        private static class ParcelContents implements Contents {
            private int i = 11;
    
            @Override
            public int value() {
                //嵌套类内部访问外围类对象报错
                //System.out.println(hello);//Error: Cannot make a static reference to the non-static field hello
                
                //嵌套类内部访问外围类的static变量
                System.out.println(name);
                return i;
            }
    
        }
    
        protected static class ParcelDestination implements Destination {
    
            private String label;
    
            private ParcelDestination(String whereTo) {
                label = whereTo;
            }
    
            @Override
            public String readLabel() {
                return label;
            }
    
            /**
             * 嵌套类的static方法
             */
            public static void f() {
            }
    
            /**
             * 嵌套类的static变量
             */
            static int x = 10;
            
            /**
             *嵌套类中的嵌套类
             */
            static class AnthorLevel {
                public static void f() {
                }
                
                static int x=10;
    
            }
    
        }
        
        
        public static Destination destination(String s) {
            return new ParcelDestination(s);
        }
        
        public static Contents contents() {
            return new ParcelContents();
        }
        
        public static void main(String[] args) {
            
            /**
             * 外围类的静态方法,此方法中是没有this引用的
             * 之前在外围类的静态方法中,需要采用如下语法
             * Parcel11 p=new Parcel11();
             * Parcel11.Destination d= p.new Destination();
             * 
             * 现在可以直接创建嵌套类
             */
            Destination d2=new ParcelDestination("test"); //直接创建嵌套类
            
            Contents c=new ParcelContents();
            
        }
    }
  • 相关阅读:
    java 异常处理
    c/c++ 多维数组和指针
    c/c++ 数组和指针
    c/c++ 数组 数组的引用,指针数组的引用
    c/c++ 标准库 迭代器(iterator)
    c/c++ 标准库 vector
    c/c++ 标准库 string
    c/c++ 模板与STL小例子系列<三> traits
    c++ 右值引用,move关键字
    c/c++ 右值引用
  • 原文地址:https://www.cnblogs.com/cplinux/p/13091484.html
Copyright © 2011-2022 走看看