Classes, Objects, and Packages in Java
Java is an object-oriented programming (OOP) language, which means it is based on the
concepts of Classes, Objects, and Packages. Let's explore each concept in detail.
1. Class in Java
A class is a blueprint or template for creating objects. It defines the properties (fields) and
behaviors (methods) that objects of the class will have.
Key Features of a Class:
- Acts as a template for objects.
- Defines properties (variables) and behaviors (methods).
- Can have constructors to initialize objects.
- Supports access modifiers (public, private, protected, default).
Syntax of a Class:
Example of a Car class:
class Car {
String brand;
int speed;
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
void displayCar() {
System.out.println("Brand: " + brand + ", Speed: " +
speed + " km/h");
}
}
2. Object in Java
An object is an instance of a class. It represents a real-world entity with attributes and
behaviors.
Creating an Object:
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 120);
myCar.displayCar();
}
}
3. Package in Java
A package is a collection of related classes and interfaces. It is used to organize code and
prevent name conflicts.
Types of Packages:
- Built-in Packages: Predefined Java packages like java.util, java.io, etc.
- User-defined Packages: Custom packages created by developers.
Creating and Using a Package:
Step 1: Create a Package
package vehicles;
public class Car {
public void display() {
System.out.println("This is a car from the vehicles
package.");
}
}
Step 2: Use the Package
import vehicles.Car;
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.display();
}
}
Summary
Concept Description
Class A blueprint for creating objects, defining
fields and methods.
Object An instance of a class that represents real-
world entities.
Package A collection of related classes and
interfaces for better code organization.