Inner Class & Anonymity

Posted nedrain

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Inner Class & Anonymity相关的知识,希望对你有一定的参考价值。

匿名子类 对 抽象类 而言, 匿名实现类 对 接口 而言

匿名子类

// Father.java
public abstract class Father {
    public abstract  void say();
}
// Say.java
public class Say {
    public void say(Father father){
        father.say();
    }
}
// Client.java
public class Client {
    public static void main(String[] args) {
        Say say = new Say();
        say.say(new Father() {
            @Override
            public void say() {
                System.out.println("I am the father.");
            }
        });
    }
}

匿名实现类

// Father.java    Here is the change
public interface Father {
    void say();
}
// Say.java
public class Say {
    public void say(Father father){
        father.say();
    }
}
// Client.java
public class Client {
    public static void main(String[] args) {
        Say say = new Say();
        say.say(new Father() {   // @Override is not allowed in implement
            public void say() {
                System.out.println("Hi, this is Tom.");
            }
        });
    }
}

以上是关于Inner Class & Anonymity的主要内容,如果未能解决你的问题,请参考以下文章

[20-05-15][Thinking in Java 18]Java Inner Class 2 - .this & .new

Android proguard,保持Inner class的inner class

[20-05-18][Thinking in Java 26]Java Inner Class 10 - Anonymous Inner Class 5

[20-05-15][Thinking in Java 17]Java Inner Class 1 - Inner Class 2

[20-05-15][Thinking in Java 17]Java Inner Class 1 - Inner Class 2

[20-05-18][Thinking in Java 25]Java Inner Class 9 - Anonymous Inner Class 4