Classes and Objects in Java
In Java, a class is a blueprint for creating objects, which are instances of classes. Classes encapsulate data for the object and methods to manipulate that data.
Key Points on Classes and Objects:
- A class defines the properties (attributes) and behaviors (methods) of an object.
- An object is an instance of a class and represents a specific realization of that class.
- Classes can have constructors, which are special methods called when an object is instantiated.
- Objects can interact with each other by calling methods and accessing attributes of other objects.
- Encapsulation allows hiding the internal state of an object and exposing only the necessary parts through methods.
- Classes can inherit from other classes, promoting code reuse and establishing a hierarchical relationship.
Syntax of a Class:
Syntax Example
public class ClassName {
// Attributes
// Constructors
// Methods
}
Example of a Class in Java:
This example demonstrates a simple class called Car with attributes and methods.
Code Example: Class Definition
public class Car {
// Attributes
String color;
String model;
// Constructor
public Car(String color, String model) {
this.color = color;
this.model = model;
}
// Method
public void displayInfo() {
System.out.println("Car Model: " + model + ", Color: " + color);
}
}
Creating Objects:
This example shows how to create objects from the Car class and call its method.
Code Example: Object Creation
public class Main {
public static void main(String[] args) {
// Creating objects
Car car1 = new Car("Red", "Toyota");
Car car2 = new Car("Blue", "Honda");
// Calling method
car1.displayInfo();
car2.displayInfo();
}
}
Output
Car Model: Toyota, Color: Red
Car Model: Honda, Color: Blue
Car Model: Honda, Color: Blue
Detailed Explanation:
- Class: Defines a data type by bundling data and methods that work on that data.
- Object: Represents an instance of a class, created using the
new
keyword. - Constructor: A special method that initializes the object’s attributes when the object is created.
- Methods: Define the behaviors of the object, allowing interaction with its attributes.
Understanding classes and objects is fundamental to mastering Java's Object-Oriented Programming (OOP) paradigm, enabling developers to create modular and reusable code.