CONSTRUCTORS
CONSTRUCTOR IN JAVA
• Constructor in java is a special type of method that is used
to initialize the object.
• Java constructor is invoked at the time of object creation.
• It constructs the values i.e. provides data for the object that
is why it is known as constructor.
NEED FOR A CONSTRUCTOR
Think of a Box. If we talk about a box class then it will have some class variables
(say length, breadth, and height). But when it comes to creating its object(i.e Box will
now exist in computer’s memory), then can a box be there with no value defined for
its dimensions. The answer is no.
So constructors are used to assign values to the class variables at the time of object
creation, either explicitly done by the programmer or by Java itself (default
constructor).
When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could
be default constructor) is invoked to assign initial values to the data members of the
same class.
A constructor is invoked at the time of object or instance creation.
RULES FOR CREATING JAVA
CONSTRUCTOR
There are basically two rules defined for the
constructor.
•Constructor name must be same as its class name
•Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
Java Default Constructor
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
Q) What is the purpose of default constructor?
Default constructor provides the default values to the object like 0, null etc.
depending on the type.
Example of default constructor that displays the default values
class Student3{
int id;
String name;
void display()
{System.out.println(id+" "+name);
}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display(); } } Output: 0 null 0 null
Explanation: In the above class, you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
JAVA PARAMETERIZED CONSTRUCTOR
Why use parameterized constructor?
• Parameterized constructor is used to provide different values to the distinct
objects.
Class Hello
{ int value;
String name;
Hello(int x, String y)
{
value=x;
name=y;
}
}
Write a program by using a class in Java with the following specifications:
Class name — Stringop
Data members:
String str
Member functions:
Stringop() — to initialize str with NULL
void accept() — to input a sentence
void encode() — to replace and print each character of the string with the second next
character in the ASCII table. For example, A with C, B with D and so on
void print() — to print each word of the String in a separate line
public class Stringop
{
private String str;
public Stringop() {
str = null;
}
public void accept() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence: ");
str = in.nextLine();
}
public void encode() {
for (int i = 0; i < str.length(); i++) {
arr[i] = (char)(str.charAt(i) + 2);
}
str = new String(arr);
System.out.println("nEncoded Sentence:");
System.out.println(str);
}
public void print() {
System.out.println("nPrinting each word on a separate line:");
int s = 0;
while (s < str.length()) {
int e = str.indexOf(' ', s);
if (e == -1)
e = str.length();
System.out.println(str.substring(s, e));
Java parameterized constructor
A constructor that have parameters is known as parameterized constructor.Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects. Example of parameterized c
Example of parameterized constructor
class Student4
{
int id;
String name;
Student4(int i,String n)
{
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();
}
}
CONSTRUCTOR OVERLOADING
• Constructor overloading in java allows to have more than one
constructor inside one Class.
• Constructor overloading is not much different than method overloading. Just
like in case of method overloading you have multiple methods with same
name but different signature, in Constructor overloading you have
multiple constructor with different signature with only difference that
Constructor doesn't have return type in Java. Those constructor will be
called as overloaded constructor .
• Overloading is also another form of polymorphism in Java which allows to
have multiple constructor with different name in one Class in java.
Constructor Overloading in Java
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
Overloadingcopy to
clipboardclass Student5{ int id; String name; int age; Student5(int i,String n){ id =
i; name = n; } Student5(int i,String n,int a){ id = i; name = n; age=a; } v
oid display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]
){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25
); s1.display(); s2.display(); } }
Constructor Overloading in Java
Example of Constructor Overloading
class Student5
{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(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[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
Java Constructor Java Method
Constructor is used to initialize the
state of an object.
Method is used to expose
behaviour of an object.
Constructor must not have return
type.
Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a
default constructor if you don't have
any constructor.
Method is not provided by compiler
in any case.
Constructor name must be same
as the class name.
Method name may or may not be
same as class name.
Difference between constructor and method in java
Define a class named BookFair with the following description:Instance variables/data
members:String bName: stores the name of the book.double price: stores the price of the book.
Member methods:
BookFair(): default constructor to initialize data members.
void input(): to input and store the name and the price of the book.
void calculate(): to calculate the price after discount. Discount is calculated based on the following
criteria:
Price Discount
Less than or equal to Rs. 1000 5 % of price
More than Rs. 1000 and less than or
equal to Rs. 3000
12 % of price
More than Rs. 3000 20 % of price
void display(): to display the name and price of the book after discount
Write a program in Java to find the roots of a quadratic equation
ax2+bx+c=0 with the following specifications:
Class name — Quad
Data Members — float a,b,c,d (a,b,c are the co-efficients & d is the
discriminant), r1 and r2 are the roots of the equation.
Member Methods:
Quad(int x,int y,int z) — to initialize a=x, b=y, c=z, d=0
void calculate() — Find d=b2-4ac
If d < 0 then print "Roots not possible" otherwise find and print:
r1 = (-b + √d) / 2a
r2 = (-b - √d) / 2a
Write a program by using a class with the following specifications:
Class name — Hcflcm
Data members/instance variables: int a, int b
Member functions:
Hcflcm(int x, int y) — constructor to initialize a=x and b=y.
void calculate( ) — to find and print hcf and lcm of both the numbers.
public class Hcflcm{
{ int a, b;
Hcflcm(int x, int y)
{ a=x and b=y;}
public void calculate()
{ int aa=a,bb=b;
while (b != 0)
{ int t = b;
b = a % b;
a = t; }
int hcf = a;
int lcm = (aa * bb) / hcf;
System.out.println("HCF = " + hcf); System.out.println("LCM = " + lcm); }
public void calculate(){
for(int i = 1; i <= a || i <= b; i++)
{ if( a%i == 0 && b%i == 0 )
hcf = i;
}
System.out.println("HCF of given two numbers is ::"+hcf); } }
psvm()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers: ");
a = sc.nextInt();
b = sc.nextInt();
Hcflcm ob=new Hcflcm(a,b);
}
}
Write a program by using a class in Java with the following specifications:
Class name — Stringop
Data members:
String str
Member functions:
Stringop() — to initialize str with NULL
void accept() — to input a sentence
void encode() — to replace and print each character of the string with the
second next character in the ASCII table. For example, A with C, B with D
and so on
void print() — to print each word of the String in a separate line

constructors.pptx

  • 1.
  • 2.
    CONSTRUCTOR IN JAVA •Constructor in java is a special type of method that is used to initialize the object. • Java constructor is invoked at the time of object creation. • It constructs the values i.e. provides data for the object that is why it is known as constructor.
  • 3.
    NEED FOR ACONSTRUCTOR Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no. So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor). When is a Constructor called ? Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class. A constructor is invoked at the time of object or instance creation.
  • 5.
    RULES FOR CREATINGJAVA CONSTRUCTOR There are basically two rules defined for the constructor. •Constructor name must be same as its class name •Constructor must have no explicit return type
  • 6.
    Types of javaconstructors There are two types of constructors:
  • 7.
    Java Default Constructor Aconstructor that have no parameter is known as default constructor. Syntax of default constructor: class Bike1 { Bike1() { System.out.println("Bike is created"); } public static void main(String args[]) { Bike1 b=new Bike1(); } }
  • 8.
    Rule: If thereis no constructor in a class, compiler automatically creates a default constructor. Q) What is the purpose of default constructor? Default constructor provides the default values to the object like 0, null etc. depending on the type.
  • 9.
    Example of defaultconstructor that displays the default values class Student3{ int id; String name; void display() {System.out.println(id+" "+name); } public static void main(String args[]){ Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); } } Output: 0 null 0 null Explanation: In the above class, you are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default
  • 10.
    JAVA PARAMETERIZED CONSTRUCTOR Whyuse parameterized constructor? • Parameterized constructor is used to provide different values to the distinct objects. Class Hello { int value; String name; Hello(int x, String y) { value=x; name=y; } }
  • 11.
    Write a programby using a class in Java with the following specifications: Class name — Stringop Data members: String str Member functions: Stringop() — to initialize str with NULL void accept() — to input a sentence void encode() — to replace and print each character of the string with the second next character in the ASCII table. For example, A with C, B with D and so on void print() — to print each word of the String in a separate line
  • 12.
    public class Stringop { privateString str; public Stringop() { str = null; } public void accept() { Scanner in = new Scanner(System.in); System.out.println("Enter a sentence: "); str = in.nextLine(); } public void encode() { for (int i = 0; i < str.length(); i++) { arr[i] = (char)(str.charAt(i) + 2); } str = new String(arr); System.out.println("nEncoded Sentence:"); System.out.println(str); } public void print() { System.out.println("nPrinting each word on a separate line:"); int s = 0; while (s < str.length()) { int e = str.indexOf(' ', s); if (e == -1) e = str.length(); System.out.println(str.substring(s, e));
  • 13.
    Java parameterized constructor Aconstructor that have parameters is known as parameterized constructor.Why use parameterized constructor? Parameterized constructor is used to provide different values to the distinct objects. Example of parameterized c Example of parameterized constructor class Student4 { int id; String name; Student4(int i,String n) { 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(); } }
  • 14.
    CONSTRUCTOR OVERLOADING • Constructoroverloading in java allows to have more than one constructor inside one Class. • Constructor overloading is not much different than method overloading. Just like in case of method overloading you have multiple methods with same name but different signature, in Constructor overloading you have multiple constructor with different signature with only difference that Constructor doesn't have return type in Java. Those constructor will be called as overloaded constructor . • Overloading is also another form of polymorphism in Java which allows to have multiple constructor with different name in one Class in java.
  • 15.
    Constructor Overloading inJava 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 Overloadingcopy to clipboardclass Student5{ int id; String name; int age; Student5(int i,String n){ id = i; name = n; } Student5(int i,String n,int a){ id = i; name = n; age=a; } v oid display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[] ){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25 ); s1.display(); s2.display(); } } Constructor Overloading in Java Example of Constructor Overloading class Student5 { int id; String name; int age; Student5(int i,String n){ id = i; name = n; } Student5(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[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display();
  • 16.
    Java Constructor JavaMethod Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object. Constructor must not have return type. Method must have return type. Constructor is invoked implicitly. Method is invoked explicitly. The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case. Constructor name must be same as the class name. Method name may or may not be same as class name. Difference between constructor and method in java
  • 17.
    Define a classnamed BookFair with the following description:Instance variables/data members:String bName: stores the name of the book.double price: stores the price of the book. Member methods: BookFair(): default constructor to initialize data members. void input(): to input and store the name and the price of the book. void calculate(): to calculate the price after discount. Discount is calculated based on the following criteria: Price Discount Less than or equal to Rs. 1000 5 % of price More than Rs. 1000 and less than or equal to Rs. 3000 12 % of price More than Rs. 3000 20 % of price void display(): to display the name and price of the book after discount
  • 18.
    Write a programin Java to find the roots of a quadratic equation ax2+bx+c=0 with the following specifications: Class name — Quad Data Members — float a,b,c,d (a,b,c are the co-efficients & d is the discriminant), r1 and r2 are the roots of the equation. Member Methods: Quad(int x,int y,int z) — to initialize a=x, b=y, c=z, d=0 void calculate() — Find d=b2-4ac If d < 0 then print "Roots not possible" otherwise find and print: r1 = (-b + √d) / 2a r2 = (-b - √d) / 2a
  • 19.
    Write a programby using a class with the following specifications: Class name — Hcflcm Data members/instance variables: int a, int b Member functions: Hcflcm(int x, int y) — constructor to initialize a=x and b=y. void calculate( ) — to find and print hcf and lcm of both the numbers. public class Hcflcm{ { int a, b; Hcflcm(int x, int y) { a=x and b=y;}
  • 20.
    public void calculate() {int aa=a,bb=b; while (b != 0) { int t = b; b = a % b; a = t; } int hcf = a; int lcm = (aa * bb) / hcf; System.out.println("HCF = " + hcf); System.out.println("LCM = " + lcm); }
  • 21.
    public void calculate(){ for(inti = 1; i <= a || i <= b; i++) { if( a%i == 0 && b%i == 0 ) hcf = i; } System.out.println("HCF of given two numbers is ::"+hcf); } } psvm() { Scanner sc = new Scanner(System.in); System.out.println("Enter the numbers: "); a = sc.nextInt(); b = sc.nextInt(); Hcflcm ob=new Hcflcm(a,b); } }
  • 22.
    Write a programby using a class in Java with the following specifications: Class name — Stringop Data members: String str Member functions: Stringop() — to initialize str with NULL void accept() — to input a sentence void encode() — to replace and print each character of the string with the second next character in the ASCII table. For example, A with C, B with D and so on void print() — to print each word of the String in a separate line