Class and Object in Java Example
Here you will get the basic program code to implement the concept of class and object in java example.
Difference between Class and Object in Java?
Class
- Think of a class as a blueprint or a recipe.
- It’s like a plan that tells you how to create something.
- In Java, a class defines what an object will be like. It’s a way to describe an object’s characteristics and behavior.
- Imagine you’re making cookies: the recipe (class) tells you what ingredients you need and how to combine them.
Example
1 2 3 4 5 6 7 8 9 | class Car { String brand; String model; int year; void startEngine() { // Code to start the car's engine } } |
Object
- An object is like the real thing you create using the blueprint (class).
- It’s the actual instance, the physical cookie you get from following the recipe.
- In Java, an object is like a container that holds data and can do things (methods).
- For example, if the class is “Car,” an object could be “MyCar,” with its own specific details like color, brand, and year.
Example
1 2 3 4 5 | Car myCar = new Car(); // Create object of Car class myCar.brand = "TATA"; // Setting attributes myCar.model = "Harrier"; myCar.year = 2023; myCar.startEngine(); // Invoking a method on the object |
Class and Object in Java Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | //Class and Object in Java Example // Define Car class class Car { // Instance variables String brand; String model; int year; // Constructor method public Car(String brand, String model, int year) { this.brand = brand; this.model = model; this.year = year; } // Method to display details public void display() { System.out.println("Brand: " + brand); System.out.println("Model: " + model); System.out.println("Year: " + year); } } class mainClass { public static void main(String[] args) { // Create objects Car car1 = new Car("TATA", "Harrier", 2023); Car car2 = new Car("Mahindra", "Scorpio", 2022); // Call methods System.out.println("Car 1 Deatils:"); car1.display(); System.out.println("\nCar 2 Details:"); car2.display(); } } |
Program Explanation
When you run this program, it will create two car objects, set their attributes, and display information about each car, demonstrating the concept of classes and objects in Java.
Output
C:\CodeRevise\java>javac mainClass.java
C:\CodeRevise\java>java mainClass
Car 1 Deatils:
Brand: TATA
Model: Harrier
Year: 2023
Car 2 Details:
Brand: Mahindra
Model: Scorpio
Year: 2022