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

Constructor

The document provides a comprehensive overview of constructors in Java, detailing their purpose, types (default and parameterized), and key characteristics such as overloading and chaining. It explains the concept of a singleton class and demonstrates how to implement it using private constructors. Additionally, the document covers methods in Java, including their definition, calling, parameter passing, and method overloading.

Uploaded by

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

Constructor

The document provides a comprehensive overview of constructors in Java, detailing their purpose, types (default and parameterized), and key characteristics such as overloading and chaining. It explains the concept of a singleton class and demonstrates how to implement it using private constructors. Additionally, the document covers methods in Java, including their definition, calling, parameter passing, and method overloading.

Uploaded by

vvarshini279
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Constructor:

Constructor are special methods which are used to initialize the object.
A constructor has same name as that of class.
It does not have any return type.
e.g. class Rock
{
Rock()
//default constructor
{}
}
If you do not provide the constructor then compiler create a default constructor.
A default constructor is a non-argument constructor.
If you create a constructor then compiler will not create default constructor for
you.
Important points for constructor:
Constructor are not inherited.
They are called in the order of inheritance.
They can be overloaded but can not be overridden.
You can not create a single object without a constructor.
‘Super’ is use to call the desired version of superclass constructor.
Call to the ‘super’ must be the first statement in constructor.
‘This’ keyword can be used for inter constructor communication.
Types of constructors:
1) Default constructor
2) Parameterized constructor
Default Constructor:
A constructor that have no parameters is known as default constructor.
It is primarily used to initialize the object with default initial values.
When no default constructor is defined by users explicitly, java provides its own
version of default constructor to initialize the object.
Syntax of Default Constructor:
e.g. class Rock
{
Rock()
//default constructor
{}
}
Example of Default Constructor:
class A
{
A()
{
System.out.println(“In A Constructor”);
}
}
class B extends A
{
B()
{
System.out.println(“In B Constructor”);
}
}
class C extends B
{
C()
{
System.out.println(“In C Constructor”);
}
public static void main(String args[])
{
C ob = new c();
}
}
Output:
In A Constructor
In B Constructor
In C Constructor
Parameterized constructor:
A constructor that have parameter is known as parameterized constructor.
Parameter are added to a constructor in the way that they are added to a method,
just declare them inside the parentheses after the constructor’s name.
Parameterized constructor is used to provide different values to the distinct
objects
Example of Parameterized Constructor:
class Student
{
int id;
String name;
Student(int i, String n) // Parameterized Constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+""+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading:
Constructor overloading is a technique in Java in which a class can have any
number of constructors that differ in parameter lists.
The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Example of Constructor Overloading:
class Student
{
int id;
String name;
int age;
Example of Parameterized Constructor:
class Student
{
int id;
String name;
Student(int i, String n) // Parameterized Constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+""+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading:
Constructor overloading is a technique in Java in which a class can have any
number of constructors that differ in parameter lists.
The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Example of Constructor Overloading:
class Student
{
int id;
String name;
int age;
Student(int i, String n)
{
id = i;
name = n;
}
Student(int i, String n, int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+""+name+""+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan 25
Copy Constructor:
There is no copy constructor in java. But, we can copy the values of one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They
are:
1. By constructor
2. By assigning the values of one object into another
3. By clone() method of Object class
In this example, we are going to copy the values of one object into another using
java
constructor
Example of Copy Constructor:
class Student
{
int id;
String name;
Student(int i, String n)
{
id = i;
name = n;
}
Student(Student s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+""+name);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Overloading Constructor

In addition to overloading normal methods, you can also overload constructor methods. In fact, for
most real-world classes that you create, overloaded constructors
will be the norm, not the exception. To Boxunderstandclass why developed in the preceding chapter.
Following is the latest version of Box:
class Box { double width; double height; double depth;
// This is the constructor for Box. Box(double w, double h, double d)
{ width = w; height = h; depth = d;
}
// compute and return volume double volume() {
return width * height * depth;
}
}

Constructor Chaining In Java


Constructor chaining is the process of calling one constructor from another
constructor with respect to current object.
One of the main use of constructor chaining is to avoid duplicate codes while
having multiple constructor (by means of constructor overloading) and make
code more readable.
Constructor chaining can be done in two ways:
 Within same class: It can be done using this() keyword for constructors in
the same class
 From base class: by using super() keyword to call the constructor from the
base class.
Constructor chaining occurs through inheritance. A sub-class constructor’s task
is to call super class’s constructor first. This ensures that the creation of sub
class’s object starts with the initialization of the data members of the superclass.
There could be any number of classes in the inheritance chain. Every constructor
calls up the chain till the class at the top is reached.
// Java program to illustrate Constructor Chaining
// within same class Using this() keyword
class Temp
{
// default constructor 1
// default constructor will call another constructor
// using this keyword from same class
Temp()
{
// calls constructor 2
this(5);
System.out.println("The Default constructor");
}

// parameterized constructor 2
Temp(int x)
{
// calls constructor 3
this(5, 15);
System.out.println(x);
}

// parameterized constructor 3
Temp(int x, int y)
{
System.out.println(x * y);
}

public static void main(String args[])


{
// invokes default constructor first
new Temp();
}
}

75
5
The Default constructor
Rules of constructor chaining :
1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword
(constructor 3 in above example).
3. Constructor chaining can be achieved in any order.

// Java program to illustrate Constructor Chaining


// within same class Using this() keyword
// and changing order of constructors
class Temp
{
// default constructor 1
Temp()
{
System.out.println("default");
}

// parameterized constructor 2
Temp(int x)
{
// invokes default constructor
this();
System.out.println(x);
}

// parameterized constructor 3
Temp(int x, int y)
{
// invokes parameterized constructor 2
this(5);
System.out.println(x * y);
}

public static void main(String args[])


{
// invokes parameterized constructor 3
new Temp(8, 10);
}
}

default
5
80
// Java program to illustrate Constructor Chaining to
// other class using super() keyword
class Base
{
String name;

// constructor 1
Base()
{
this("");
System.out.println("No-argument constructor of" +
" base
class");
}

// constructor 2
Base(String name)
{
this.name = name;
System.out.println("Calling parameterized constructor"
+ "
of base");
}
}

class Derived extends Base


{
// constructor 3
Derived()
{
System.out.println("No-argument constructor " +
"of derived");
}

// parameterized constructor 4
Derived(String name)
{
// invokes base class constructor 2
super(name);
System.out.println("Calling parameterized " +
"constructor of derived");
}

public static void main(String args[])


{
// calls parameterized constructor 4
Derived obj = new Derived("test");

// Calls No-argument constructor


// Derived obj = new Derived();
}
}
Calling parameterized constructor of base
Calling parameterized constructor of derived
Note : Similar to constructor chaining in same class, super() should be the first line
of the constructor as super class’s constructor are invoked before the sub class’s
constructor.

Like any method we can provide access specifier to the constructor. If it’s made
private, then it can only be accessed inside the class.
There are various scenarios where we can use private constructors. The major ones
are
1. Internal Constructor chaining
2. Singleton class design pattern
What is a Singleton class?
As the name implies, a class is said to be singleton if it limits the number of objects
of that class to one.
We can’t have more than a single object for such classes.
Singleton classes are employed extensively in concepts like Networking and
Database Connectivity.
Design Pattern of Singleton classes:
The constructor of singleton class would be private so there must be another way to
get the instance of that class. This problem is resolved using a class member
instance and a factory method to return the class member.
// Java program to demonstrate implementation of Singleton
// pattern using private constructors.
import java.io.*;

class MySingleton
{
static MySingleton instance = null;
public int x = 10;

// private constructor can't be accessed outside the class


private MySingleton() { }

// Factory method to provide the users with instances


static public MySingleton getInstance()
{
if (instance == null)
instance = new MySingleton();

return instance;
}
}

// Driver Class
class Main
{
public static void main(String args[])
{
MySingleton a = MySingleton.getInstance();
MySingleton b = MySingleton.getInstance();
a.x = a.x + 10;
System.out.println("Value of a.x = " + a.x);
System.out.println("Value of b.x = " + b.x);
}
}
We changed value of a.x, value of b.x also got updated because both ‘a’ and ‘b’
refer to same object, i.e., they are objects of a singleton class

A method in Java is a block of code that, when called, performs specific actions
mentioned in it. For instance, if you have written instructions to draw a circle in the
method, it will do that task. You can insert values or parameters into methods, and
they will only be executed when called. They are also referred to as functions. The
primary uses of methods in Java are:

 It allows code reusability (define once and use multiple times)

 You can break a complex program into smaller chunks of code

 It increases code readability

Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b) {
// body
}
Here,

public static − modifier


int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is
shown in the following syntax −
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes −

modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.

Example
/** the snippet returns the minimum between two numbers */
publicstaticint minFunction(int n1,int n2){
int min;
if(n1 > n2)
min = n2;
else
min = n1;

return min;}

Method Calling
For using a method, it should be called. There are two ways in which a method is
called i.e., method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then returns
control to the caller in two conditions, when −

 the return statement is executed.


 it reaches the method ending closing brace.
The methods returning void is considered as call to a statement. Lets consider an
example −
System.out.println("This is tutorialspoint.com!");
The method returning value can be understood by the following example −
int result = sum(6,9);
Following is the example to demonstrate how to define a method and how to call it −
Example
Live Demo
publicclassExampleMinNumber{
publicstaticvoid main(String[] args){
int a =11;
int b =6;
int c = minFunction(a, b);
System.out.println("Minimum Value = "+ c);
}

/** returns the minimum of two numbers */


publicstaticint minFunction(int n1,int n2){
int min;
if(n1 > n2)
min = n2;
else
min = n1;

return min;
}}
Passing Parameters by Value
While working under calling process, arguments is to be passed. These should be in
the same order as their respective parameters in the method specification. Parameters
can be passed by value or by reference.
Passing Parameters by Value means calling a method with a parameter. Through this,
the argument value is passed to the parameter.
Example
The following program shows an example of passing parameter by value. The values
of the arguments remains the same even after the method invocation.
Live Demo
publicclass swappingExample {

publicstaticvoid main(String[] args){


int a =30;
int b =45;
System.out.println("Before swapping, a = "+ a +" and b = "+ b);

// Invoke the swap method


swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same
here**:");
System.out.println("After swapping, a = "+ a +" and b is "+ b);
}

publicstaticvoid swapFunction(int a,int b){


System.out.println("Before swapping(Inside), a = "+ a +" b = "+ b);

// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = "+ a +" b = "+ b);
}}
This will produce the following result −
Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45
Method Overloading
When a class has two or more methods by the same name but different parameters, it
is known as method overloading. It is different from overriding. In overriding, a
method has the same method name, type, number of parameters, etc.
Let’s consider the example discussed earlier for finding minimum numbers of integer
type. If, let’s say we want to find the minimum number of double type. Then the
concept of overloading will be introduced to create two or more methods with the
same name but different parameters.
The following example explains the same −
Example
Live Demo
publicclassExampleOverloading{

publicstaticvoid main(String[] args){


int a =11;
int b =6;
double c =7.3;
double d =9.4;
int result1 = minFunction(a, b);

// same function name with different parameters


double result2 = minFunction(c, d);
System.out.println("Minimum Value = "+ result1);
System.out.println("Minimum Value = "+ result2);
}

// for integer
publicstaticint minFunction(int n1,int n2){
int min;
if(n1 > n2)
min = n2;
else
min = n1;

return min;
}
// for double
publicstaticdouble minFunction(double n1,double n2){
double min;
if(n1 > n2)
min = n2;
else
min = n1;

return min;
}}
This will produce the following result −
Output
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given by the
same name but with different parameters. The minimum number from integer and
double types is the result.

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