0 votes
in JAVA by
What are anonymous inner classes?

1 Answer

0 votes
by
Anonymous inner classes are the classes that are automatically declared and instantiated within an expression. We cannot apply different access modifiers to them. Anonymous class cannot be static, and cannot define any static fields, method, or class. In other words, we can say that it a class without the name and can have only one object that is created by its definition. Consider the following example.

abstract class Person{  

  abstract void eat();  

}  

class TestAnonymousInner{  

 public static void main(String args[]){  

  Person p=new Person(){  

  void eat(){System.out.println("nice fruits");}  

  };  

  p.eat();  

 }  

}  

Test it Now

Output:

nice fruits

Consider the following example for the working of the anonymous class using interface.

interface Eatable{  

 void eat();  

}  

class TestAnnonymousInner1{  

 public static void main(String args[]){  

 Eatable e=new Eatable(){  

  public void eat(){System.out.println("nice fruits");}  

 };  

 e.eat();  

 }  

}  

Test it Now

Output:

nice fruits

Related questions

0 votes
asked May 5, 2021 in JAVA by SakshiSharma
+1 vote
asked May 5, 2021 in JAVA by SakshiSharma
...