• Home
  • Android
  • Programming
    • Object Oriented Programming
  • PHP
  • Contact

bitcaal.com

  • Home
  • Android
  • Programming
    • Object Oriented Programming
  • PHP
  • Contact

Object-Oriented Programming Concepts: Constructor & Destructor

bymehadi March 2, 2020 Object Oriented Programming

In this lecture, i will talk about the Constructors & Destructors in Java.

Table Of Contents

  1. Constructor
  2. Constructor Overloading
  3. Destructor

Constructor

A constructor is as special method which is used to initialize objects when creating the object. When we create an object from a class the constructor is called. It is used to set some initial values to the object attributes.

  • A constructor can have parameter or it can be empty.
  • A constructor  is called just after the memory is allocated for the object.

Example

public class ExampleClass {
    String name;
    public ExampleClass(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

    public static void main(String[] args) {
       ExampleClass example = new ExampleClass("Mehadi Hasan");
       System.out.println(example.getName());
    }
}

Constructor Overloading

We know that methods can be overloaded, in the same way a constructor can also be overloaded. When we have more than one constructor with different parameters we call it constructor overloading. By doing this we can perform different task for each constructor.

Example

public class ExampleClass {
    String name;


    public ExampleClass() {
        this.name = "Default Name";
    }

    public ExampleClass(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public static void main(String[] args) {

        ExampleClass def = new ExampleClass();
        System.out.println(def.getName());

        ExampleClass example = new ExampleClass("Mehadi Hasan");
        System.out.println(example.getName());
    }
}

Destructor

When the life-cycle of an object is completed a destructor is called. A destructor is also a special method which is called to free the used memory. In Java the destructors are known as finalizers. The allocation and release of memory are implicitly handled by the garbage collector in Java.

 

5 Best New Latest Technology

Rubik's Cube, 3D Combination Puzzle

Leave a Reply Cancel reply

two − two =

Recent Posts

  • Remove null values from an Array in PHP
  • Rubik’s Cube, 3D Combination Puzzle
  • Object-Oriented Programming Concepts: Constructor & Destructor
  • 5 Best New Latest Technology
  • How to Change The App Language Programmatically in Android

Categories

  • Android Basic
  • Object Oriented Programming
  • PHP
  • Programming
  • Technology

Recent Comments

  • JohnDoes on How to Change The App Language Programmatically in Android
© bitcaal 2020