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:
| Rule | Description |
|---|---|
| Same name as class | Constructor name must match the class name |
| No return type | A constructor cannot have a return type, not even void |
| Called automatically | It is called automatically when an object is created |
| Used for initialization | Used to initialize the object's state |
| Can be overloaded | A 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:
| Usage | Description |
|---|---|
| Refer to instance variable | Used when parameter and instance variable have the same name |
| Call current method | this.drive() calls the current object's method |
| Call current constructor | this() calls another constructor of the same class |
| Pass current object | this 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:
| Point | Description |
|---|---|
| Belongs to class | Shared by all objects of the class |
| Single copy | Only one copy of a static variable exists per class |
| Access using class name | Can be accessed using ClassName.member |
| No object required | Static members can be accessed without creating an object |
| Commonly used for utility methods | Example: 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.
| Member | Belongs To |
|---|---|
| Instance variable | Object |
| Instance method | Object |
| Static variable | Class |
| Static method | Class |
Next TopicEncapsulation