Advertisement
Google Ad Slot: content-top
Java Class and Object
Java is an object-oriented programming language where the building blocks are classes, fields, constructors, methods, and objects. Let’s understand each of them in detail.
Class:
- A class is a blueprint for creating objects. It defines the fields (attributes) and methods (behavior) that an object will have.
Syntax:
class ClassName {
// Fields
// Constructors
// Methods
}
Example
class Car {
// This is a class named Car
}
Fields:
- Fields are variables declared within a class. They define the properties or attributes of the class and its objects.
Syntax:
class ClassName {
DataType fieldName; // Field declaration
}
Example
class Car {
String brand; // Field: brand of the car
int speed; // Field: speed of the car
}
Constructor:
A constructor is a special method used to initialize an object. It is automatically called when an object is created.
- The name of the constructor must be the same as the class name.
- It does not have a return type.
Syntax:
class ClassName {
ClassName() {
// Constructor logic
}
}
Example
class Car {
String brand;
int speed;
// Constructor
public Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
}
Methods:
- A method defines a behavior or functionality of the class. Methods are blocks of code that perform specific tasks and can return a value.
Syntax:
class ClassName {
ReturnType methodName(Parameters) {
// Method logic
}
}
Example
class Car {
String brand;
int speed;
// Constructor
public Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
// Method to display car details
public void displayDetails() {
System.out.println("Brand: " + brand + ", Speed: " + speed + " km/h");
}
}
Object:
- An object is an instance of a class. It represents a specific entity that has its own state and behavior defined by the class.
Syntax:
ClassName objectName = new ClassName();
Example
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Toyota", 120);
// Accessing the object's method
myCar.displayDetails(); // Output: Brand: Toyota, Speed: 120 km/h
}
}
Multiple Objects:
You can create multiple objects of one class:
Example
// Main class to use the Car class
public class Main {
public static void main(String[] args) {
// Creating objects of the Car class
Car car1 = new Car("Toyota", 120);
Car car2 = new Car("Honda", 100);
// Accessing methods of the Car objects
car1.displayDetails(); // Output: Brand: Toyota, Speed: 120 km/h
car2.displayDetails(); // Output: Brand: Honda, Speed: 100 km/h
car1.accelerate(30); // Output: Toyota accelerated to 150 km/h
car2.accelerate(20); // Output: Honda accelerated to 120 km/h
}
}