user2843171
user2843171

Reputation: 43

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

Upvotes: 0

Views: 122

Answers (5)

UVM
UVM

Reputation: 9914

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. Because of these two reasons, "display" method is getting invoked.

Upvotes: 0

Volodymyr Krupach
Volodymyr Krupach

Reputation: 918

You extended Twenty class from B class: class Twenty extends A.B. Than you call display() on instance of the Twenty so inherited display method is invoked.

Upvotes: 0

Ashok_Pradhan
Ashok_Pradhan

Reputation: 1169

As class Twenty extends from class B it can access its non private methods .(Simple )

Upvotes: 0

wam090
wam090

Reputation: 2873

Simple inheritance, Twenty calling the ".super()" from its constructor and since Twenty extends A & B then calling the method "display()" will give you this result

Upvotes: 0

Muhammad Kashif Nazar
Muhammad Kashif Nazar

Reputation: 23935

This is as simple as a class Twenty extending a class B.

Since there is a method display in the B class, Twenty inherits this method as if this method is declared in it. This is why you are able to call the display method on an object of the class Twenty which is abc.

Upvotes: 2

Related Questions