Java puzzle 24: Anonymous class demonstration

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 
>

An anonymous class is a class, which doesn’t have a name.
It is used once to override methods of a class or an interface.
For more about anonymous classes you can click here.

Note: The class Anonymous and the interface Length are two separate files in the same package.

Java puzzle 24: Anonymous class demonstration

Level: Normal

What is the output of this program and why?

Length.java

public interface Length
{
  int x = 8;
  
  void getMessage(String message);
  void getNumber(int i);
}

Anonymous.java

public class Anonymous
{
  int x = 6;
  
  public static void main(String[] args)
  {
    Anonymous an = new Anonymous();
    Length length = new Length()
    {
      public void getMessage(String str)
      {
        System.out.print(str + x);
      }
      public void getNumber(int i)
      {
        System.out.print("x" + i);
      }
    };
    length.getMessage("y");
  }
}
Author: Sar Maroof

Answer explanation

  1. The statement length.getMessage(“y”); invokes the method getMessage. The statement System.out.print(str + x); writes the parameter str and the value of the variable x┬áto the standard output. The parameter str is y and the variable x refers to the variable x inside the interface Length. So, it writes y8 to the standard output.
  2. The method getNumber is not invoked. So, the statement┬áSystem.out.print(“x” + i); will not be executed.

The answer is: y8.





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *