Home > Java > javaTutorial > body text

Defining a Package

Linda Hamilton
Release: 2024-09-29 06:07:02
Original
597 people have browsed it

Definindo um Pacote

Package relevance:
All classes belong to a package.
The default (global) package is used if none is specified, but is not suitable for large projects.

Creating a package:
Use the package statement at the beginning of a source file.
The package statement defines a namespace for the classes in the file.

Example package definition:
package mypack;

Package management in the file system:
Each package is stored in its own directory on the file system.
The directory must have the same name as the package, taking case into account.

Package hierarchy:
Packages can be organized hierarchically with multiple levels.

Example of package hierarchy:
package alpha.beta.gamma;

In the file system, this hierarchy will be reflected as .../alpha/beta/gamma.

Shared use of packages:
Multiple files can include the same package statement, allowing multiple classes to be part of the same package.

Code Example
Directory Structure:

src/
  mypack/
    MyClass.java
  Main.java

Copy after login
  1. Defining a Package (mypack/MyClass.java):
package mypack;

public class MyClass {
    public void displayMessage() {
        System.out.println("Olá do pacote mypack!");
    }
}

Copy after login
  1. Using the Package Class (Main.java):
import mypack.MyClass;  // Importando a classe MyClass do pacote mypack

public class Main {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();  // Criando uma instância de MyClass
        myClass.displayMessage();  // Chamando o método da classe
    }
}

Copy after login

Explanation:
The mypack package was defined in the MyClass.java file with the package.
statement The MyClass class belongs to the mypack package, being accessed and used in the main Main class through import mypack.MyClass.

Program output:
Hello from mypack!

The above is the detailed content of Defining a Package. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!