zoukankan      html  css  js  c++  java
  • java 匿名内部类

    匿名内部类适合只需要使用一次的对象

    匿名内部类常用于实现某个接口,也可以继承父类

    如实现Fruit接口,一般方法为:

    interface  Fruit {
    
        public abstract void type() ;
    }
    
    // 创建一个新类实现Fruit接口
    class Apple implements Fruit { public void type() { System.out.println("It's apple"); } }

    使用Apple类创建一个对象

    public class Test {
    
        public static void main(String args[])  {
    
            Fruit obj = new Apple();
        }
    }

    而使用匿名内部类:

    public class Test {
    
        public static void main(String args[])  {
    
            Fruit obj = new Fruit(){
                public void type() {
                    System.out.println("It's apple");
                }
            };
        }
    }

    也可用于继承父类

    public class Test {
    
        public static void main(String args[])  {
    
            Fruit orange = new Fruit(){
    
                // 重写introduce方法
                public void introduce() {
                    System.out.println("This is orange");
                    System.out.println(a);
                }
            };
    
            orange.introduce();
        }
    }
    
    
    class Fruit {
    
        int a = 10;
        public void introduce() {
            System.out.println("This is fruit");
        }
    }
  • 相关阅读:
    H3C 配置vlan及vlan间路由
    H3C 端口安全技术
    H3C 备份系统应用程序与文件
    H3C 类似于Linux编辑命令
    H3C telnet
    H3C基本命令
    Python里的目录
    Python 模块
    Python 函数
    JS 100内与7相关的数
  • 原文地址:https://www.cnblogs.com/deltadeblog/p/8400736.html
Copyright © 2011-2022 走看看