简体   繁体   English

用Java解释匿名类

[英]Explain anonymous Class in Java

When the program is run display function gets called. 当程序运行时,显示函数被调用。 But not able to understand how? 但是不能理解如何?

class A
{
    class B
    {
        void display()
        {
            System.out.println("display in B.....");
        }
    }
}

class Twenty extends A.B
{
    Twenty(A temp)
    {
       temp.super();
    }
    public static void main(String args[])
    {
        A obj=new A();
        Twenty abc=new Twenty(obj);
        abc.display();
    }
}

explain this program 解释这个程序

This is as simple as a class Twenty extending a class B . 这就像扩展B类的Twenty类一样简单。

Since there is a method display in the B class, Twenty inherits this method as if this method is declared in it. 由于B类中存在方法display ,因此Twenty继承此方法,就好像在其中声明了此方法一样。 This is why you are able to call the display method on an object of the class Twenty which is abc . 这就是为什么你能够在类Twenty的对象上调用display方法的原因是abc

简单的继承,Twenty从它的构造函数调用“.super()”,因为Twenty扩展A&B然后调用方法“display()”将给你这个结果

由于类Twenty从B类扩展,它可以访问其非私有方法。(简单)

你从B类扩展了Twenty类:class Twenty extends AB比你在Twenty实例上调用display()所以调用了继承的显示方法。

You can access inner class method from an outer class. 您可以从外部类访问内部类方法。 Here outer class is A and that is the object you are passing to constructor in your main method.Also, it obeys inheritance. 这里的外部类是A,它是你在main方法中传递给构造函数的对象。它也遵循继承。 Because of these two reasons, "display" method is getting invoked. 由于这两个原因,“显示”方法被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM