Saturday, November 8, 2008

Many Public Classes in 1 Java File !!

There is a popular misconception among the beginners that we can have multiple public classes in one java source file.
But the rule is that "we can have atmost one public class and any number of non-public classes in one .java source file". The public class must contain the main method, from where the execution begins. As i see it, this is so that JVM could access and call the main method from outside the class. 

However, there is one exception to this rule. I wrote this blog entry because i came to know about the exception :)
The exception comes when we deal with inner classes. You can have as-many-as-you-want public inner classes in your class. But, it is not desirable as it results in difficult-to-manage code and of decreases its re-usability. 

For example, the following code would compile and run successfully.
>
>  class tryme
>  {
>     public static class A
>   {
>   public void print()
>   {   System.out.println(" Print inside A ");   }
>   }
>
>   public static class B
>   {
>   public void display()
>   {   System.out.println(" Display inside B ");   }
>   }
>
>  }
>
>  public class test
>  {
>   public static void main(String[] args)
>   {
>   tryme.A ob = new tryme.A();
>   ob.print();
>
>   tryme.B ob2 = new tryme.B();
>   ob2.display();
>     }
>  }
>

Of course, the file must be named test.java. It compiles and produces the following output.
>
> Print inside A
> Display inside B
>

Another way of using public inner classes is by importing them in your program like
import packagename.tryme.*;
and then use classes A and B as they you like.

But, the recommended style of programming discourages use of more than one public class in one java file. Also, such behaviour is not supported on all compilers. Infact, for maximum optimization (by compiler) it is recommended that you should write one class per java file.

Comments and corrections are welcome. :)

No comments: