/* related posts with thumb nails */

Creating a package with multiple classes:

Creating multiple classes in a package: In java, one program can have only one public class. If at all, there are more non-public classes in a same program, they will not become the members of a package. But, to have multiple classes in a single package, the directory is going to be same; while the classes are to be written in different programs.

The following example shows step-by-step approach to create a package with multiple classes.

· First create a directory by name “Arithmetic” and move to that directory

· Create the following file (file name should be Sum.java) and compile the file in the same directory.

package arithmetic;

public class Sum

{

public int add(int x,int y)

{

return x+y;

}

}

· Create the second file (file name should be Difference.java) and compile the file in the same directory.

package arithmetic;

public class Difference

{

public int sub(int x,int y)

{

return x-y;

}

}

· Now, Move to parent (working) directory, write the following file (Test.java) and execute it.

import arithmetic.*;

class Test

{

public static void main(String as[])

{

Sum s1 = new Sum();

System.out.println(s1.add(8,5)); // prints 13

Difference d1 = new Difference ();

System.out.println(d1.sub(8,5)); // prints 3

}

}

Related Topics:

0 comments:

Post a Comment