Skip to main content

Practical-29

Write a java program which shows importing of classes from other packages.


Introdution

Java uses packages as a concept to modularize and maintain the code. The packages help a user to identify certain classes/interfaces as belonging to certain packages. To use classes in packages they need to be imported and this is an example of how to import classes from other packages in Java.

Code

package p1;
public class Main {
public static void main(String[] args) {
package p2;
class C {
void cMethod() {
System.out.println("cMethod of class c.");
}
}
C c = new C();
c.cMethod();
}
}

Output

cMethod of class c.
Explanation

The above code shows an example of how to import classes from other packages in Java. It creates an instance of the class declared in a different package, p2, and calls one of its methods.