In Java, a class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects created from the class will have. Classes are fundamental to object-oriented programming (OOP) in Java, allowing for encapsulation, inheritance, and polymorphism.
Key Components of a Java Class:
Class Declaration:
- A class is declared using the
classkeyword followed by the class name. - Example:
public class Car { }
- A class is declared using the
Attributes (Fields):
- Attributes are variables that hold the state of an object. They define the properties of the class.
- Example:
public class Car { String color; String model; int year; }
Methods:
- Methods define the behaviors of the class. They are functions that can operate on the attributes of the class.
- Example:
public class Car { String color; String model; int year; void start() { System.out.println("The car is starting."); } }
Constructor:
- A constructor is a special method that is called when an object is instantiated. It usually initializes the attributes of the class.
- Example:
public class Car { String color; String model; int year; // Constructor public Car(String color, String model, int year) { this.color = color; this.model = model; this.year = year; } }
Access Modifiers:
- Access modifiers (like
public,private, andprotected) control the visibility of classes, methods, and attributes. - Example:
public class Car { ... }makes the class accessible from other classes.
- Access modifiers (like
Example of a Complete Java Class:
public class Car {
// Attributes
String color;
String model;
int year;
// Constructor
public Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
}
// Method to display car details
void displayDetails() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
System.out.println("Car Year: " + year);
}
}
// Main class to test the Car class
public class Main {
public static void main(String[] args) {
// Creating an object of Car
Car myCar = new Car("Red", "Toyota", 2020);
myCar.displayDetails(); // Calling the method to display details
}
}
Explanation:
- The
Carclass has attributes for color, model, and year. - It includes a constructor to initialize these attributes.
- The
displayDetailsmethod prints the car's details. - The
Mainclass demonstrates how to create an object of theCarclass and call its method.
If you have any further questions or need more examples, feel free to ask!
