Calling a class in another file

This example demonstrates how to call a class placed in another file. contains the class A with the metod add. B:java calls this method.

DOS and notepad are used for the example.

1. Use notepad to create A class - Save the file as

package util;

public class A {
public int add(int x, int y){
return (x + y);

2. Use notepad to create B class - Save file as

import util.A;

public class B {
public static void main(String args[]){
A a = new A();
System.out.println("Result: " + a.add(3, 5));

3. Place the and in a directory on yout classpath (In this example c:\jar)

4. Compile package

javac -classpath c:\jar

5. Create a new subdirectoy under the current directory named util

Note that it is important to give the subdirectory exactly the same name as the utillity package (See

6. Move A.class to the util subdirectory

7. Compile

javac -classpath c:\jar

8. Run

java -cp c:\jar B

- Result: 8

Converted from CHM to HTML with chm2web Standard 2.7 (unicode)