0% found this document useful (0 votes)
27 views

Constructor

Here are the programs to print student details using constructors and find area of rectangle using constructors: 1. Student class with default and parameterized constructor: class Student{ String name; String dept; int roll; Student(){ name="Ankit"; dept="SCHEME"; roll=1; } Student(String name, String dept, int roll){ this.name=name; this.dept=dept; this.roll=roll; } void display(){ System.out.println(name+" "+dept+" "+roll); } public static void main(String[] args) { Student s1=new Student();

Uploaded by

clashbros563
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Constructor

Here are the programs to print student details using constructors and find area of rectangle using constructors: 1. Student class with default and parameterized constructor: class Student{ String name; String dept; int roll; Student(){ name="Ankit"; dept="SCHEME"; roll=1; } Student(String name, String dept, int roll){ this.name=name; this.dept=dept; this.roll=roll; } void display(){ System.out.println(name+" "+dept+" "+roll); } public static void main(String[] args) { Student s1=new Student();

Uploaded by

clashbros563
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Constructor

What is a constructor?

As a class-based object-oriented programming term, a constructor is a unique method


used to initialize a newly created object (class). There are a few rules you must follow
when creating constructors. These rules include:

•The name of the constructor must be the same as the class name.

•The constructor must have no return type.

Before we proceed, let's see what a class looks like in Java:

public class Student {


String firstName;
String lastName;
int age;
}
Java Constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object
of a class is created. It can be used to set initial values for object attributes:

// Create a Main class


public class Main {
int x; // Create a class attribute

// Create a class constructor for the Main class


public Main() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


Main myObj = new Main(); // Create an object of class Main
(This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}

// Outputs 5
The code above shows a class called Student with three attributes – firstName, lastName, and age.
We will assume that the class is supposed to be a sample for registering students. Recall that the
three attributes do not have any values so none of the information is hard coded.

Now we will use constructors to create a new instance of our Student object. That is:
public class Student {
String firstName;
String lastName;
int age;

//Student constructor
public Student(){
firstName = “Ankit";
lastName = “Mishra";
age = 20;
}

public static void main(String args[]) {


Student myStudent = new Student();
System.out.println(myStudent.age);
// 20
}
}
What is a default constructor?

A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a class. Here is an example:

public class Student {


String firstName;
String lastName;
int age;

/* empty constructor created by compiler. This constructor will not be


seen in your code */
Student() {

public static void main(String args[]) {


Student myStudent = new Student();

myStudent.firstName = "Ankit";
myStudent.lastName = "Mishra";
myStudent.age = 20;

System.out.println(myStudent.age);
//20

System.out.println(myStudent.firstName);
Output
//Ankit 20
} Ankit
}
Java compiler automatically creates a default constructor (Constructor with no arguments) in
case no constructor is present in the java class. Following are the motive behind a default
constructor.

Create the Object

Call the super class constructor()

Initialize all the instance variables of the class object.


Parameterized Constructor

A constructor with one or more parameters is called as


parameterized constructor.

Why parameterized constructor is used?

Parameterized constructor is used to provide the initial values to


the object properties (initial state of object). By use of
parameterized constructor different objects can be initialize with
different data member values or states.
public class ParameterizedConstructor {
int num;
String str;

ParameterizedConstructor (int n, String s){


System.out.println("Parameterized Constructor called.");
num = n;
str = s;
}

public static void main(String args[]){


//constructor call
ParameterizedConstructor object = new
ParameterizedConstructor (10, "SCHEME");

//print values of object properties


System.out.println("num = " + object.num);
System.out.println("str = " + object.str);
}
}

Output
Parameterized Constructor called.
num = 10
str = SCHEME
Constructor Overloading
•In Java, it is possible to create methods that have the same
name, but different parameter lists and different definitions.
This is called method overloading.

•Method overloading is used when objects are required to


perform similar tasks but using different input parameters. When
we call a method in an object, Java matches up the method
name first and then the number and type of parameters to
decide which one of the definitions to execute. This process is
known as polymorphism.
Java Destructor
In Java, when we create an object of the class it occupies some space in the memory (heap). If we do not delete these
objects, it remains in the memory and occupies unnecessary space that is not upright from the aspect of programming. To
resolve this problem, we use the destructor.

The destructor is the opposite of the constructor. The constructor is used to initialize objects while the destructor is
used to delete or destroy the object that releases the resource occupied by the object.

What is the destructor in Java?


It is a special method that automatically gets called when an object is no longer used. When an object completes its
life-cycle the garbage collector deletes that object and deallocates or releases the memory occupied by the object.
It is also known as finalizers that are non-deterministic. In Java, the allocation and deallocation of objects handled by
the garbage collector. The invocation of finalizers is not guaranteed because it invokes implicitly.
Advantages of Destructor
•It releases the resources occupied by the object.
•No explicit call is required, it is automatically invoked at the end of the program execution.
•It does not accept any parameter and cannot be overloaded.
Java finalize() Method
It is difficult for the programmer to forcefully execute the garbage collector to destroy the object. But Java provides an
alternative way to do the same. The Java Object class provides the finalize() method that works the same as the
destructor. The syntax of the finalize() method is as follows:

Syntax:
protected void finalize throws Throwable()
{
//resources to be close
}
Example of Destructor
public class DestructorExample
{ Output:
public static void main(String[] args)
{
DestructorExample de = new DestructorExample ();
de.finalize();
de = null; Object is destroyed by the Garbage Collector
System.gc(); Inside the main() method
System.out.println("Inside the main() method"); Object is destroyed by the Garbage Collector
}
protected void finalize()
{
System.out.println("Object is destroyed by the Garbage
Collector");
}
}
1. Write a java programme to print the student name, department, and roll
no using default constructor and parameterized constructor.
(student name: Ankit, Department: SCHEME, Roll No. 1)

1. Write a programme to find the Area of rectangle with parameterized


constructor and default constructor, where length and breadth for default
constructor are 15 m and 35 m and for parameterized constructor are 15
m and 15 m.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy