Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding interface

 
Damodar Mukhopadhyay
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we cannot create objects of an interface then how this code compiles successfully! I am confused!!! please make me understand why this Annonymous reference compiled and what is its usage. The code is given below.


interface I {} // line 1
class A {
public static void main(String args[])
{
I aa = new I(){}; // line no 5

}

}

is this is treated as a class in line no 5. If so then in the below code given what is happening actually?

class A {

interface I{}
I aa = new I(){};

}
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In the above class you have declared a nested interface I. On the next line you have a reference aa to an object that implements the interface I.
You have initialized the reference aa to an instance of an anonymous subclass of the class Object that implements the interface I.
[ February 06, 2007: Message edited by: Barry Gaunt ]
 
Damodar Mukhopadhyay
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry Barry, I cant get You. Can you please describe it?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unfortunately I cannot see how I can reduce it any further. It's just the basic Java stuff
Anybody else?
 
sentil kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A {
interface I{
void show();
}
I aa1 = new I(){
public void show(){
System.out.println("anonymous inner class one method");
}
};
I aa2 = new I(){
public void show(){
System.out.println("anonymous inner class two method");
}
};
public static void main(String[] a1){
A a = new A();
a.aa1.show();
a.aa2.show();

}
}

I is a inner interface.
aa is pointing to Object of anonymous class which implements I.

after compiling the above code, you see three class file
A$I(nested interface).class,A$1(anonymous class).class,A.class(enclosing class)

compile and run the above sample code
 
Damodar Mukhopadhyay
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok ok I got it. Actualy the rule was not known to me.
So I can say in this situation the Object class implicitly involbs and will implement the interface.
Thank you very much.
 
Damodar Mukhopadhyay
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks A lot to Both of you. I got My answer and many more.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic