Forum : OBJECTS AND CLASSES
Brief description  about Online courses   join in Online courses
View AJANTA  MAHATO 's Profile

OBJECTS AND CLASSES

Is it possible to create many public classes in one program?
Kindly have a look at the program below:-

public class Me
{
int age;
String name;

public void age(int value)
{
age=value;
}

void name(String string)
{
name=string;
}

public void printname()
{
System.out.println("My name is " name );
}

public void printage()
{
System.out.println("My age is " age " years");
}
}

public class Myself
{

public static void main(String args[])
{
Me m=new Me();
m.name("Ajanta");
m.printname();
}
}

public class Myself1
{
public static void main(String args[])
{

Me m1=new Me();
m1.age(22);
m1.printage();
}
}
error message thrown on compiling the program as-
javac Myself.java
C:\Program Files\Java\jdk1.6.0\bin>javac Myself.java
Myself.java:1: class Me is public, should be declared in a file named Me.java
public class Me
^
Myself.java:38: class Myself1 is public, should be declared in a file named Myse
lf1.java
public class Myself1
^
2 errors

C:\Program Files\Java\jdk1.6.0\bin>

While compiling as:- javac Myself1.java doesnt throw any error.

Kindly have a look at the following at the prog which runs successfully:-

class Me
{
int age;
String name;

public void age(int value)
{
age=value;
}

void name(String string)
{
name=string;
}

public void printname()
{
System.out.println("My name is " name );
}

public void printage()
{
System.out.println("My age is " age " years");
}
}

class Myself
{

public static void main(String args[])
{
Me m=new Me();
m.name("Ajanta");
m.printname();
}
}

class Myself1
{
public static void main(String args[])
{

Me m1=new Me();
m1.age(22);
m1.printage();
}
}


PLease explain the reason, why is the program behaving like that?????
Asked by AJANTA MAHATO | Feb 20, 2010 |  Reply now
Replies (1)
View arun kumar das 's Profile
Hi Ajanta,

I am very happy that you have tried this. Of-course, its possible to use lot of public classes in one program but I recommend that you use separate .java files for each class. It will be like cooking tasty celicacies and mixing them all and serving.

If you still want to use many public classes in one programme then the best way I suggest is to use packages. Even using packages will make your code very complicated and result in huge source files. This can be used when we include 5 to 10 classes in a programme but in reality we will be using hundreds of classes which will result in chaos if weuse it in one program. Please develop a habit of writing classes in separate .java files.

Thanks,
Java Teacher
Feb 23, 2010