Introduce Java Classes and Objects and give examples
Java is an object-oriented programming language that uses classes and objects as its fundamental building blocks. Understanding classes and objects is essential for writing effective Java programs.
A class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects created from the class will have. A class can contain:
An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. Objects can interact with each other and can be manipulated using methods defined in their class.
Let's create a simple example to illustrate classes and objects in Java.
public class Car {
// Fields (attributes)
private String color;
private String model;
private 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
public void displayDetails() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
System.out.println("Car Year: " + year);
}
// Method to change the color of the car
public void repaint(String newColor) {
this.color = newColor;
System.out.println("The car has been repainted to: " + newColor);
}
}
Now, let's create objects of the Car
class and use its methods.
public class Main {
public static void main(String[] args) {
// Creating objects of the Car class
Car car1 = new Car("Red", "Toyota", 2020);
Car car2 = new Car("Blue", "Honda", 2018);
// Displaying details of car1
car1.displayDetails();
// Repainting car1
car1.repaint("Green");
// Displaying details of car2
car2.displayDetails();
}
}
Class Definition: The Car
class has three fields: color
, model
, and year
. It also has a constructor to initialize these fields and two methods: displayDetails()
to print the car's details and repaint()
to change the car's color.
Creating Objects: In the Main
class, we create two objects of the Car
class (car1
and car2
) using the new
keyword and the constructor.
Using Methods: We call the displayDetails()
method on both objects to print their details. We also call the repaint()
method on car1
to change its color.
Classes and objects are central to Java programming. They allow for encapsulation, inheritance, and polymorphism, which are key principles of object-oriented programming. By defining classes and creating objects, you can model real-world entities and their interactions in your programs.