OOP

Constructor, this, static

1. Constructor

A constructor is a special method used to initialize an object.

There are some important rules that need to be followed when creating a constructor:

RuleDescription
Same name as classConstructor name must match the class name
No return typeA constructor cannot have a return type, not even void
Called automaticallyIt is called automatically when an object is created
Used for initializationUsed to initialize the object's state
Can be overloadedA class can have multiple constructors with different parameters
class Car {
String brand;
int speed;
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
}
Car car = new Car("BMW", 120);

Here, Car(String brand, int speed) is a parameterized constructor that initializes the object's brand and speed.

2. this

The this keyword refers to the current object of a class.

There are several common situations where the this keyword is used:

UsageDescription
Refer to instance variableUsed when parameter and instance variable have the same name
Call current methodthis.drive() calls the current object's method
Call current constructorthis() calls another constructor of the same class
Pass current objectthis can be passed as an argument
class Car {
String brand;
int speed;
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
void drive() {
System.out.println(brand + " is driving at " + speed + " km/h");
}
}

Here, this.brand refers to the instance variable, while brand refers to the constructor parameter.

3. static

The static keyword is used to define members that belong to the class rather than individual objects.

There are some important points to remember about static members:

PointDescription
Belongs to classShared by all objects of the class
Single copyOnly one copy of a static variable exists per class
Access using class nameCan be accessed using ClassName.member
No object requiredStatic members can be accessed without creating an object
Commonly used for utility methodsExample: Math.max()
class Car {
static int numberOfCars = 0;
Car() {
numberOfCars++;
}
}
Car car1 = new Car();
Car car2 = new Car();
System.out.println(Car.numberOfCars); // 2

Here, numberOfCars belongs to the Car class, so it is shared by all Car objects.

MemberBelongs To
Instance variableObject
Instance methodObject
Static variableClass
Static methodClass
Next TopicEncapsulation