匿名内部类的使用

  • Post author:
  • Post category:其他


##直接代码

package com.fang.java.javabase.innerclass;

import java.util.jar.Attributes.Name;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
public class AnonymousClasses {
    Animal outan;

    interface HelloWorld {
        void greet();

        void greetsomeone(String someone);
    }

    // 内部类
    class Animal {
        public String name="default";
        public Animal() {

        }
        public Animal(String name) {
            this.name = name;
        }

        public void printName() {
            log.info("Animal:" +this.name);
        }
        public String getName(){
            return name;
        }


    }

    public void outFun() {
        log.info("out function");

    }

    //匿名类通过外部的调用外部的变量
    public Animal getAni(final String args) {
        return new Animal() {
            public void printName() {
                outFun();
                log.info("Animal:" + args);
            }

        };
    }
    //通过实例初始化来调用外部的局部变量
    public Animal getAni2(String args) {
        return new Animal(args) {
            public void printName() {
                outFun();
                //log.info("Animal:" + getName());如果nane是private
                log.info("Animal:" + name);
            }

        };
    }

    public static void main(String[] args) {
        AnonymousClasses ac = new AnonymousClasses();
        HelloWorld helloWorld = new HelloWorld() {
            private String input;

            @Override
            public void greetsomeone(String someone) {
                log.info("hello " + someone);
            }

            @Override
            public void greet() {
                log.info("hello world" );
            }
        };
        //接口的匿名内部类实现
        helloWorld.greet();
        helloWorld.greetsomeone("jack");

        //类的匿名内部类的实现
        ac.getAni("buguliao").printName();;

        ac.getAni2("xiaoji").printName();

        //内部类的调用方式
        ac.new Animal("da e"){
            public void printName() {
                log.info("Animal:"+name);
            }
        }.printName();
    }
}



版权声明:本文为u010886216原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。