Anonymous Class -


Anonymous Class -

An anonymous class is a class that does not have any name. It is normally used to create objects of abstract classes.

Example -

abstract class Marks
{
    private int phy,chem;
   
    public void input()
    {
        phy = Integer.parseInt(System.console().readLine("Enter physics marks"));
        chem = Integer.parseInt(System.console().readLine("Enter chemistry marks"));
    }
    
    public void disp()
    {
        System.out.println(phy+"    "+chem);
    }
 
}

     
        
public class Call {

    public static void main(String[] args) {
    
      Marks m1= new Marks() {
          };
      m1.input();
      m1.disp();
    } 
}

    
Here the statement Marks m1= new Marks() { }; will create a anonymous class like this -
class  ------------- extends Marks
 {
 }
 
That is class does not have any name and extends Marks class, so now we can create object and access members of Marks class.
If Marks class also contain some abstract methods (as in Example 3) then they also need to be override like this -
public class Call {

    public static void main(String[] args) {
    
      Marks m1= new Marks() 
      {
          public void disp()
          {
              System.out.println("Just a Demo");
          }
      };
      m1.input();
      m1.disp();
      m1.show();
    } 
}

         
The statements -
Marks m1= new Marks() 
      {
          public void disp()
          {
              System.out.println("Just a Demo");
          }
      };

Will create a anonymous class like this -
class -------------------------  extends Marks      // class with no name
{
     public void disp()
          {
              System.out.println("Just a Demo");
          }
}