Object Oriented Programming(OOP) Series: Constructor and Destructor

In this series as promised earlier we’ll be brushing up OOP concepts in the most simplest form with examples in PHP, Javascript and Dart.

So far in this series we’ve covered Classes & Objects , Attributes & Methods.

A Class can be a parent of many objects while an object is a child of a class. Inside the class closure{} variables are called attributes(data members) and the functions inside that get or set values are called methods.

Next let’s look at constructors and destructors

Constructor

An object or something that is used to design another object or build an object is called a constructor.

Basically in simple terms it’s responsible to design and describe what the class expects from or is passing to its object upon creation or access and also it can be seen as a method that is automatically invoked and executed when an object is created from a class. It’s a unique member function in a class responsible for initializing the expected parameters or behavior of its objects upon creation (instantiation).

The idea of it been unique is that it can take the name of the class. For example if we’ve a constructor in the Car class it can be called upon to get the information of a car objects upon creation because every car should have an information. The constructor will automatically construct the attributes (data members) of a Car for the new object (Toyota).

A constructor is solely responsible for initiating the object for behavior, specifically instantiating initial values for all its attributes in the class.

Note: arguments are parameters passed into a function or method or in our case a constructor.

Types of Constructor:

Default constructor: a constructor that accepts no arguments into the class or object.

Parameterized constructor: constructor that accepts arguments for manipulation or evaluation of data members and methods.

Copy constructor: there are scenarios where we need to adjust the constructor of a class we can do this by referencing the class of the constructor as it’s argument or parameter.

Overloaded constructor: occurs when there are multiple things to automatically execute in a class automatically by defining multiple constructors.

The constructor method is defined to ease the process of initializing the data attributes within a class. Note: constructors are optional in a class and some object oriented languages can automatically create one for you when there is none.

Destructor

A destructor is a unique method that is invoked to destroy or unset a constructor after it’s been called automatically to construct something for its class or object. So if we call a constructor to accept the information of a car as arguments we will need to unset the objects when the constructor is destroyed for memory optimization and performance issues. In some languages it’s preceded by ~ or __

A destructor can also be referred to as clean up.

Destructors de-initialize class objects when they are destroyed. Destructors execute behind the scenes when the objects are destroyed by the built in Garbage Collection facility. Destructors are also optional and does not accept arguments or return a value. We can have only one destructor defined in a class.

In the next part of this series we’ll be looking at Access Modifiers.

Please note: The examples below are used to illustrate the concepts and not to define their full meaning in the languages. Simple illustration in Javascript

class Car{
constructor(type, model) {
this.type = type;
this.model = model;
}
}
let toyota = new Car("Toyota", "Camry");console.log(toyota);//output is Car {type: "Toyota", model: "Camry"}class Car{
constructor() {
console.log('Default constructor');
}
}
let toyota = new Car();//out put is Default constructor

constructor(type, model) is a parameterized constructor because it accept two arguments.

let toyota = new Car(“Toyota”, “Camry”); while creating an object for the Car class it expects two values(one for type and the other for model) as seen in this code.

example of default constructor

constructor() { console.log(‘Default constructor’);

}

Destructuring in Javscript is quite different from the approach of OOP.

const toyota= { year: ‘2018’, model: ‘C1’ };

const {year, model} = toyota;

console.log(year); // 2018 console.log(model); // C1

Simple illustration in Dart:

class Car{
Car();
}
//this class constructor has no arguments and is referred to as default constructorclass Car{
String model;
Car(this.model);
Car.make(this.model);Car.fromCompany(Car another) :
color = another.color,
name = another.name;
Car.empty(); //will u
}
void main(){
var toyota = new Car('Toyota Camry'); //accessing the Car parameterized constructor
}

Car(this.model); //this class constructor accepts one argument and is referred to as parameterized constructor

Car.make(this.model); is an example of a named constructor it allows for overloaded constructor(defining multiple constructor)

Car.fromCompany(Car another) //the car constructor is referenced in another constructor

The main() method is a constructor in Dart that’s automatically executes the code inside it’s closure.

Dart is a garbage-collected language, so any object that you don’t hold any references to will eventually be garbage collected and freed by the runtime system.

Simple illustration in PHP

In PHP, there are two ways we can write a constructor method inside a class.

create a method with the name __construct() inside the class. create a method naming exactly the same as class name. Using our Car class for example we can create a constructor by using the name Car().

<?phpclass Car
{
private string $name;
//Parameterized constructor Before PHP 8
public function __construct(string $name): void
{
$this->name = $name;
}
//Parameterized constructor in PHP 8
public function __construct(private string $name){}
//Default constructor
public function __construct()
{
return 'default constructor';
}
/**
A destructor is called when the object is destructed or the script is stopped or exited.
PHP will automatically call the __destruct method at the end of this script.
**/
public function __destruct(){
}}?>

Stay tune for the next article on the OOP Series: Access Modifiers

Thank you for reading this article. Please feel free to use the comment section for questions, answers and contributions.

You love this article?? please follow me on hashnode or twitter @alemsbaja to stay updated for more on these OOP series.

Originally published at https://alemsbaja.hashnode.dev.

--

--

--

Software developer | information professional | librarian | writer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Aspects to consider while building an app like Tiktok: The features and technology stack required

Power Automate — Getting to Grips with Action Request Limits

How to build a serverless Laravel queue using AWS Lambda

Things you may find hard to believe (or not)

Hadoop Cluster Automation with Ansible!!

Citrix 1Y0-341 Exam Prep Tips: Schedule Your Certification

https://www.vmexam.com/citrix/citrix-1y0-341-ccp-n-certification-exam-syllabus

Union Find — Data Structure in Python

Genymotion vs Android Emulator

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alemoh Rapheal B. Enike

Alemoh Rapheal B. Enike

Software developer | information professional | librarian | writer

More from Medium

PHP fundamentals — part 1

Solid Principles

pre_fetch_count in common cases in PHP

INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING IN PHP