0% found this document useful (0 votes)
12 views12 pages

Understanding Java Constructors

A constructor is a special method in a class that is used to initialize objects of that class. Constructors have the same name as the class, have no return type, and are automatically called when an object is created. There are different types of constructors including default, parameterized, and copy constructors. Constructors allow objects to be created and initialized with initial values.

Uploaded by

sheela
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views12 pages

Understanding Java Constructors

A constructor is a special method in a class that is used to initialize objects of that class. Constructors have the same name as the class, have no return type, and are automatically called when an object is created. There are different types of constructors including default, parameterized, and copy constructors. Constructors allow objects to be created and initialized with initial values.

Uploaded by

sheela
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Constructor

Definition

 A constructor is a special member method of a class that is automatically


called while creating an object to initialize its elements(data member /
attributes).
 It has the same name as the class name.
 It has no return type,not even void.
 Constructors should be declared in the public section of the Class.
 The constructor is called (invoked) automatically when an object of a class
is created.

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Rules for creating Java constructor

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Need for constructor:

 Create instance of class.(means creating an object)


 It can be used to set initial values for object attributes(variables) of a
class .

class Test
{

public Test() // Constructor

// body of constructor

Invoking a constructor

 Constructors are invoked automatically when we create objects for the class.

Syntax:

<class name><>obj name> = new <constructor / class name>;

Example:

Test obj= new Test();

Here, Test() will invoke the default constructor.

Why should we define a constructor public.

 By defining public , the objects can be created in any method.


 The constructor can be called outside the class(by creating object)
 Hence the access specifier of a constructor is always public.
Characteristics /Features

 Used to initialize the data [Link] arithmatic or logical operations are


performed in a constructor.

 Constructors name must be similar to that of the class name inside which it
[Link] allows the constructors to be invoked automatically on object
creation.)
 Constructors are automatically(implicitly) called when an object is created.

Item ob=new item();

 Constructors cannot be private.


 A constructor cannot be abstract, static, final.
 A constructor can be overloaded.
 Constructors cannot return a value.
 Constructors do not have a return type; not even void.

Reason : Constructors are used to initialize the data [Link] arithmatic


or logical operations are performed in a [Link] return from
constructor is not required.

 An abstract class can have the constructor.


 Constructors cannot be inherited; but can be accessed by a subclass
(Reason: instance variables and methods of a class are known as members of a
class. Constructors are not [Link] this reason, constructors cannot be
inherited; but can be accessed by a subclass

Types of constructors
a) Parameterised constructor
b) Non Parameterised constructor
c) Default constructor
d) Copy constructor

Parameterised constructor

A parameterised constructor is a member method with same name as the class


name which is used to initialize the instance variables with the help of parametric
values (given as arguments) , passed at the time of creating an object.

Class student

int regno;

String name;

char section;

float average;

student(int x, String y, char z, float f) // Parameterised constructor

regno =x;

name = y;

section=z;

average=f;
}

Void display ()

[Link](x);

[Link](y);

[Link](z);

[Link](f);

Public static void main(String args[])

Student stu = new student(5,”Sheela”,’A’,23.4); // parameterised constructor

[Link]();

}}

// if user did not create object, we have to run the

Program differently to understand that compiler creates its own object( Page 397)

Non Parameterised constructor

A constructor which initialises the instance variables with definite values readily
available within it is called as non – parameterised constructor.

Class student

{
int regno;

String name;

student() // Non – parameterised constructor

regno =10;

name = “Sheela”;

Void display ()

[Link](x);

[Link](y);

[Link](z);

[Link](f);

Public static void main(String args[])

Student stu = new student(); // calling non parameterised constructor

[Link]();

}}

Default constructor:
 The constructor which is used to initialise the data members with default
initial values(0,null,empty values) is called as default constructor.
 We need not explicitly define a default constructor as the compiler will
supply a default constructor.

Class student

int regno;

String name;

char section;

float marks;

Void display ()

[Link](regno);

[Link](name);

[Link](section);

[Link](marks);

Public static void main(String args[])

Student stu = new student(); // calling default constructor

[Link]();
}}

Output:

Null

(empty )

0.0

Note :

 Defining a constructor with arguments hides the default constructor.


 With Parameterised constructor for a class , one must provide initial values
as arguments , otherwise compiler will report an error .

Copy constructor

A constructor that is used to initialize the instance variables of an object by


copying the initial values of the instance variables from another object.

2 Types

a) Direct entry copy constructor


b) Copy constructor by passing object.

Direct entry copy constructor

The initial values of an object is copied by assigning it to another object .

Example:

class copycon
{

int a; // instance variable

copycon(int x) // Parameterised constructor

a=x;

public static void main (String srgs[])

Copycon ob=new copycon(5); // paramerised constructor call

Copycon ob1=ob; // Direct entry copy constructor

Copy constructor by passing object.

Here object is passed to the constructor and the instance variables of current object
are initialised by copying the values from object passed to the constructor.

Example:

class copycon

int a; // instance variable

copycon(int x) // Parameterised constructor

{
a=x;

copycon(copycon ob) //copy constructor by passing object

a=ob.a;

public static void main (String srgs[])

copycon ob=new copycon(5); // paramerised constructor call

copycon ob1=ob; // Direct entry copy constructor

copycon ob1=new copycon(ob) // Copy constructor by passing object

use of constructors

Constructor overloading.

 It is the process of using a number of constructors with the same name but
having different parameter list.
 The compiler differentiates the constructor by taking into account the
number of parameters in the list and their type.
 If a class contains more than one constructors then they are overloading
constructor.
Example:

class copycon

int a; // instance variable

copycon( ) // Non – parameterised constructor

a=10;

copycon(int x) // Parameterised constructor

a=x;

copycon(copycon ob) //Copy constructor by passing object

a=ob.a;

public static void main (String srgs[])

copycon ob=new copycon(); // Non - paramerised constructor call

copycon ob=new copycon(5); // paramerised constructor call

copycon ob1=ob; // Direct entry copy constructor


copycon ob1=new copycon(ob) // Copy constructor by passing object

Difference between constructor and method.

Page 401

Common questions

Powered by AI

Constructor overloading enhances the flexibility of a class by allowing it to be instantiated with different sets of initial conditions, depending on the needs of the client code. This allows developers to set various initial states for objects using a suitable signature that fits their specific context or application environment. However, if not implemented carefully, it can lead to code duplication, where similar initialization logic is repeated across multiple constructors, or create confusion if there is ambiguous constructor resolution. Moreover, maintaining several overloaded constructors can complicate refactoring and increase maintenance burden .

A copy constructor is a special type of constructor used to create a new object as a copy of an existing object. In direct assignment, a new object references the same memory location as the original, potentially leading to unintended side-effects when the object's data is changed. In contrast, a copy constructor by passing an object creates a new object with its own memory allocation that duplicates the values of the original object's data members, thereby ensuring the independence of the new object from changes made to the original .

When a class includes a parameterized constructor, the compiler does not automatically provide a default constructor, potentially causing issues if the class later requires instantiation without arguments. If no default constructor is explicitly defined, attempts to create an object without parameters will result in a compilation error. This necessitates that developers explicitly define a no-argument constructor alongside parameterized ones to ensure seamless object creation regardless of the arguments provided in the instantiation process .

In Java, constructors cannot have a return type because their primary purpose is to initialize an object's state rather than to perform computations or operations that need to return a result. This distinction ensures that constructors are automatically invoked upon object creation and ensures no ambiguities about returning control to the caller, as would be the case with methods that return values. Practically, this rule enforces constructors to be solely used for setup and initialization, making it clear when an object enters a usable state immediately after instantiation .

The primary function of a constructor in a class is to initialize the object's attributes when it is created. Unlike regular methods, constructors are automatically invoked when an object is instantiated, and they cannot return a value, not even void. Constructors differ from methods in that they do not have a return type and are specifically used for initializing data members rather than executing actions or computations. Additionally, constructors have the same name as the class and are used to ensure that the object starts off in a valid state with defined initial values for its attributes .

Constructors in Java cannot be abstract, static, final, or synchronized because they possess unique roles that are inherently incompatible with these modifiers. A constructor is meant to instantiate an object and complete its setup, requiring concrete execution rather than abstract or static contexts. The final modifier implies immutability, which is irrelevant since constructors do not return a value. Furthermore, synchronization does not apply since each constructor call naturally constructs a distinct object instance. These restrictions ensure constructors are devoted exclusively to initialization tasks and do not partake in behaviors typical of methods .

A parameterized constructor in Java initializes the object's instance variables using values provided as arguments at the time of object creation, allowing customized initialization. This enables the same class to be instantiated with different data. In contrast, a non-parameterized constructor assigns predefined default values to the object's instance variables, which are hardcoded within the constructor itself. This means all objects created using a non-parameterized constructor will have the same initial values for their attributes .

A Java class can have multiple constructors through a process called constructor overloading, where each constructor has a unique parameter list. This allows the same class to be instantiated with different forms of initialization. The compiler distinguishes between constructors by examining the number and types of parameters in the constructor calls. When a constructor is called with specific arguments, the compiler selects the constructor whose parameter list best matches the provided arguments, ensuring the right initialization logic is applied .

A non-parameterized constructor initializes an object by setting its instance variables to predefined values coded within the constructor itself, despite not receiving any external parameters. This type of constructor is particularly useful for creating objects with consistent, often 'default', states across all instances, such as initializing configuration objects with standard settings before they are customized further by the program. This ensures a consistent baseline and can eliminate repetitive assignment code for attributes in early object design stages .

Constructor overloading in Java allows classes to have multiple constructors with different parameter lists, enabling various initialization methods. This is advantageous in scenarios like creating objects with different initial data based on context. For example, in a "Rectangle" class, overloading constructors allow creating a rectangle by specifying both width and height, using default values, or perhaps by copying another rectangle. This flexibility simplifies object creation by adapting to various initialization needs within the same class structure .

You might also like