Packages in Java | User defined packages with example | How to Create and Import a Package

Описание к видео Packages in Java | User defined packages with example | How to Create and Import a Package

User-defined packages in Java are a way to group related classes, interfaces, and sub-packages under a common name. This helps in organizing code, avoiding name conflicts, and improving code reusability. Here's a quick guide on how to create and use user-defined packages in Java:

1. Creating a Package
To create a package, use the package keyword followed by the package name.
The package statement should be the first line in the Java source file (before any imports or class declarations).

// File: MyPackage/MyClass.java
package MyPackage;

public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyPackage!");
}
}

2. Compiling the Package
To compile a class that belongs to a package, use the -d option in javac to specify the destination directory for the package structure.
javac -d . MyPackage/MyClass.java
This command compiles MyClass.java and places the compiled .class file in the corresponding directory structure.

3. Using the Package
To use a class from your custom package in another class, you need to import the package.
// File: TestPackage.java
import MyPackage.MyClass;

public class TestPackage {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
}
}

4. Compiling and Running the Program
Compile the TestPackage.java file using the javac command:
javac TestPackage.java

Run the compiled TestPackage class:
java TestPackage

Output: Hello from MyPackage!

5. Package Naming Conventions
Package names are typically written in all lowercase to avoid conflicts with class names.
They usually follow the reverse domain name convention (e.g., com.example.myapp) for larger projects.

6. Nested Packages
You can create nested packages (sub-packages) to further organize your code.
package MyPackage.SubPackage;

Import and use the nested package similarly:
import MyPackage.SubPackage.SubClass;


public class SubClass {
public void show() {
System.out.println("Hello from SubPackage!");
}
}

Комментарии

Информация по комментариям в разработке