
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Class with a constructor to initialize instance variables in Java
Constructors are special methods in Java that are invoked when an object is instantiated. They are typically used to initialize instance variables of a class. In this article, we will explore how to create a class with a constructor to initialize instance variables in Java.
Creating a Class with a Constructor
To create a class with a constructor, you define the class and then create a constructor that has the same name as the class. The constructor accepts parameters to initialize instance variables.
Example
In the example below, we have a class named 'Car' with three instance variables: 'model','year', and 'price'. The constructor takes three parameters to initialize these variables. The 'displayDetails' method is used to print the details of the car.
public class Car { String model; int year; double price; // Constructor to initialize instance variables public Car(String model, int year, double price) { this.model = model; this.year = year; this.price = price; } // Method to display car details public void displayDetails() { System.out.println("Model: " + model); System.out.println("Year: " + year); System.out.println("Price: " + price); } public static void main(String[] args) { // Creating an object of Car class using the constructor Car car1 = new Car("Toyota Camry", 2020, 24000.00); Car car2 = new Car("Honda Accord", 2021, 26000.00); // Displaying car details car1.displayDetails(); System.out.println(); car2.displayDetails(); } }
When you run the above code, it will output:
Model: Toyota Camry Year: 2020 Price: 24000.0 Model: Honda Accord Year: 2021 Price: 26000.0
In conclusion, constructors in Java are important for initializing instance variables when creating objects. They allow you to set up the state of an object at the time of its creation, making sure that the object is ready for use immediately after instantiation.