In this lesson, you will learn
Packages in Java are used to group related classes, interfaces, sub-packages, and enumerations together.
This organization helps manage and maintain the code efficiently, prevents naming conflicts by categorizing classes into different namespaces, and controls access with visibility options.
A package works as a container for classes and other sub-packages, allowing a modular programming approach
Syntax
package pkg;
Here, pkg
is the name of the package
Examples
package vehicles;
package vehicles.car; //subpackage
package com.jcodebook;
package com.jcodebook.blog;
Creating a package named ‘vehicles’
package vehicles;
public class Car {
public void display() {
System.out.println("This is a Car");
}
}
Creating a sub-package named luxury inside vehicles
package vehicles.luxury;
public class LuxuryCar {
public void display() {
System.out.println("This is a Luxury Car");
}
}
There are two ways of import statement:
import packagename.ClassName; // To import a particular class only
import packagename.*; // To import the whole package
The below examples show how to import a particular class from a package.
import vehicles.Car; //Importing a class 'Car'
import vehicles.luxury.LuxuryCar; //Importing a class 'LuxuryCar'
public class AccessCar {
public static void main(String[] args) {
Car objCar=new Car();
objCar.display();
LuxuryCar objLuxuryCar=new LuxuryCar();
objLuxuryCar.display();
}
}
Output
This is a Car
This is a Luxury Car
Creating a package named ‘com.jcodebook.blog’
package com.jcodebook.blog;
public class Chat {
public void message() {
System.out.println("Blogging......");
}
}
Creating another package named ‘com.jcodebook.platform’
package com.jcodebook.platform;
public class Chat {
public void message() {
System.out.println("Platform......");
}
}
package com.jcodebook;
import com.jcodebook.blog.Chat;
public class Apps {
public static void main(String[] args) {
Chat blogChat=new Chat();
blogChat.message();
com.jcodebook.platform.Chat platform=new com.jcodebook.platform.Chat();
platform.message();
}
}
Output
Blogging......
Platform......
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.