wellnwill Marathahalli Bangalore

Anonymous inner class


A class defined inside other class without specifying the name is called Anonymous inner class. The usage of this class is if we have one time requirement to override parent class method in child class.


Anonymous inner class which extends one class

class Juice
{
 void makeJuice()
 {
  System.out.println("mixed fruit");
 }
}
class OrangeJuice extends Juice
{
 void makeJuice()
 {
  System.out.println("orange fruit");
 }
}
class TestJuice
{
 public static void main(String args[])
 {
  Juice j1=new OrangeJuice();
  j1.makeJuice();
 }
}







class Juice
{
 void makeJuice()
 {
  System.out.println("mixed fruit");
 }
}
class OrangeJuice
{
 void makeJuice()
 {
  System.out.println("orange fruit");
 }
}
class TestJuice{
 public static void main(String args[])
 {
Juice j1=new Juice()//child object with parent reference
  {
  void makeJuice()
  {
  System.out.println("orange fruit");
  }
  };
  j1.makeJuice();
 }
}

Anonymous inner class which implements one interface

Anonymous inner class can implement only one interface and can extend only one class but not both together. Constructor will not be a part of anonymous inner class as there is no name of anonymous class.


class A
{
 public synchronized void show()
 {
  System.out.println("How are you");
  System.out.println("i am");
  System.out.println("good");
 }
}
class Test 
{
public static void main(String args[])
{
Runnable r1=new Runnable()
{
public void run()
{
A a1=new A();
a1.show();
}
};
Thread t=new Thread(r1);
t.start();
}
}

Footer with Map