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");
        }
    }
  • 相关阅读:
    集合综合练习<三>
    集合综合练习<二>
    集合综合练习<一>
    java打分系统
    mysql存储过程
    mysql的视图、索引、触发器、存储过程
    mysql
    Java 集合底层原理剖析(List、Set、Map、Queue)
    HashMap底层实现
    Gradle
  • 原文地址:https://www.cnblogs.com/deltadeblog/p/8400736.html
Copyright © 2011-2022 走看看