classes and objects in java are fundamental concepts where a class is a blueprint that defines the properties and behaviors of objects. It serves as a template for creating objects and can contain variables, methods, and constructors. A class can also define the relationships between objects and provide a structure for organizing code.
Table of Contents
Classes in Java
Let’s say we have a class called Car that defines the properties and behaviors of cars.
public class MathUtils {
public static int add(int num1, int num2) {
return num1 + num2;
}
public static int subtract(int num1, int num2) {
return num1 - num2;
}
public static int multiply(int num1, int num2) {
return num1 * num2;
}
public static double divide(int num1, int num2) {
if (num2 == 0) {
throw new IllegalArgumentException("Cannot divide by zero");
}
return (double) num1 / num2;
}
}
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 3);
System.out.println("Sum: " + sum);
int difference = MathUtils.subtract(5, 3);
System.out.println("Difference: " + difference);
int product = MathUtils.multiply(5, 3);
System.out.println("Product: " + product);
double quotient = MathUtils.divide(5, 3);
System.out.println("Quotient: " + quotient);
}
}
Output

Objects in Java
An object is an instance of a class, created by calling the constructor of the class. An object can access and manipulate the variables and methods defined in the class, and it can also interact with other objects. For example, let’s create two objects of the Car class:
public class Main {
public static void main(String[] args) {
Person person1 = new Person("John Doe", 30);
person1.printDetails();
Person person2 = new Person("Jane Smith", 25);
person2.printDetails();
person1.setName("Johnny Doe");
person1.setAge(31);
person1.printDetails();
}
}
Output

Conclusion
classes and objects are fundamental concepts in Java programming. Understanding how to create and use classes and objects is essential for building robust and scalable applications. Whether you are building a simple application or a complex system, classes and objects provide a way to organize your code, encapsulate data and behavior, and model real-world objects.