0% found this document useful (0 votes)
25 views40 pages

Week 5 - L13-L15

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)
25 views40 pages

Week 5 - L13-L15

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
You are on page 1/ 40

Subject Name: OOP

Unit No:2
Unit Name: Classes and Objects

Faculty Name : Mr. Dayanand Dhongade


Index

Lecture 13 – Constructor Overloading 3

Lecture 14 – Recursion 24

2
Module No 2: Classes and Objects

Lecture No: 13
Constructor Overloading
Constructors

• Java allows objects to initialize themselves when they are created


through the use of a constructor.

• Constructors play the role of initializing objects

• Constructors are a special kind of methods that are invoked using the
new operator when an object is created.

• Constructor in java is used to create the instance of the class.

4 Lecture 13- Constructor Overloading


Constructors

• Constructors have following properties:


 Constructors must have the same name as the class itself.

 Constructors do not have a return type— not even void.

 The implicit return type is class itself

 Constructors are invoked when the objects are created.

 A constructor with no parameters is referred to as a default


constructor and constructor with parameters is called as
parameterized constructor

Lecture 13- Constructor Overloading


Types of Constructor

Constructor

Default constructor Parameterized Constructor

6 Lecture 13- Constructor Overloading


Default Constructor

 If we don’t provide a constructor, then java provides default


constructor implementation for us to use.

 Default constructor only role is to initialize the object and return


it to the calling code.

 Default constructor is always without argument and provided by


java compiler only when there is no existing constructor defined.

 Most of the time we are fine with default constructor itself as


other properties can be accessed and initialized through getter
setter methods.

7 Lecture 13- Constructor Overloading


Program 1 for Default constructor

class Bike1{

//creating a default constructor

Bike1(){System.out.println("Bike is created");}

//main method

public static void main(String args[]){

//calling a default constructor

Bike1 b=new Bike1();

8 Lecture 13- Constructor Overloading


Program 2 for Default constructor

class Box { class BoxDemo1 {


double width; public static void main(String args[]) {
double height;
double depth; // declare, allocate, and initialize Box objects
// This is the constructor for Box.
Box mybox1 = new Box(); //constructor invoked
Box() {
Box mybox2 = new Box(); //constructor invoked
System.out.println("Constructing Box");
width = 10;
height = 10; double vol;
depth = 10; // get volume of first box
} vol = mybox1.volume();
// compute and return volume System.out.println("Volume is " + vol);
double volume() {
return width * height * depth; // get volume of second box
} vol = mybox2.volume();
} System.out.println("Volume is " + vol);
}
}

22 Lecture 13- Constructor Overloading


Parameterized Constructor

• Constructor with arguments is called parameterized constructor.

• The purpose of a parameterized constructor is to assign user-


wanted specific values to the instance variables of different objects.

10 Lecture 13- Constructor Overloading


Program 1 for Parameterized constructor

class Student4 {
int id;
String name;
Student4 (int i,String n) { //creating a parameterized constructor
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);} //method to display the values

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan"); //creating objects and passing values
Student4 s2 = new Student4(222,"Aryan");
s1.display(); //calling method to display the values of object
s2.display();
}
}
11 Lecture 13- Constructor Overloading
Program 2 for Parameterized constructor

class Box { class BoxDemo2 {


double width; public static void main(String args[]) {
double height; // declare, allocate, and initialize Box objects
double depth; Box mybox1 = new Box(10, 20, 15);
// This is the constructor for Box. Box mybox2 = new Box(3, 6, 9);
Box(double w, double h, double d) { double vol;
width = w;
height = h; // get volume of first box
depth = d; vol = mybox1.volume();
} System.out.println("Volume is " + vol);
// compute and return volume
double volume() { // get volume of second box
return width * height * depth; vol = mybox2.volume();
} System.out.println("Volume is " + vol);
} }
}

12 Lecture 13- Constructor Overloading


Constructor Overloading

• Similar to method overloading we can also overload constructor .

• Overloaded constructors have the same name but must differ in the type
and/or number of their parameters.

• They are differentiated by the compiler by the number of parameters in the


list and their types.

13 Lecture 13- Constructor Overloading


Example-1

class Box { class OverloadCons {


double width; public static void main(String args[]) {
double height; // create boxes using the various constructors
double depth; Box mybox1 = new Box(10, 20, 15);
// constructor used when all dimensions specified
Box mybox2 = new Box();
Box(double w, double h, double d) {
Box mycube = new Box(7);
width = w;
height = h; double vol;
depth = d; // get volume of first box
} vol = mybox1.volume();
// constructor used when no dimensions specified System.out.println("Volume of mybox1 is " + vol);
Box() { // get volume of second box
width = -1; // use -1 to indicate vol = mybox2.volume();
height = -1; // an uninitialized System.out.println("Volume of mybox2 is " + vol);
depth = -1; // box // get volume of cube
} vol = mycube.volume();
// constructor used when cube is created
System.out.println("Volume of mycube is " + vol);
Box(double len) {
}
width = height = depth = len;
} }
// compute and return volume
double volume() {
return width * height * depth;
}
}

14 Lecture 13- Constructor Overloading


Example-2

class Add { void addition() {


int a,b; int res=a+b;
double x,y,z; double res1=x+y+z;
Add() { System.out.println(“Result1=”+ res);
System.out.println(“Result2=”+ res1);
a=0;
}
b=0; }
x=0.0;
y=0.0; class OverloadCons {
z=0.0; public static void main(String args[]) {
}
Add(int m, int n) { Add a1=new Add();
a=m; a1.addition();
b=n;
} Add a2=new Add(3,4);
a2.addition();
Add(double p, double q, double r) {
x=p; Add a3=new Add(1.2,4.0,3.2);
y=q; a3.addition();
z=r; }}
}

15 Lecture 13- Constructor Overloading


Exercise

• WAP to create class rectangle and calculate area and perimeter of


it by using constructor.

• WAP to create class Student. Add methods to read and display


student information by using constructor.

16 Lecture 13- Constructor Overloading


Passing Object as an Argument

• We can pass class’s objects as arguments and also return them


from a function the same way we pass and return other variables.
• No special keyword or header file is required to do so.
• To pass an object as an argument we write the object name as the
argument while calling the function the same way we do it for other
variables.
• Syntax:
function_name(object_name);

17 Lecture 13- Constructor Overloading


Example: Passing Object as an Argument

class Rectangle
{
int length, width;
Rectangle(int l, int b)
{ length = l; width = b; }
void area(Rectangle r1)
{
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
}
class RectangleDemo
{
public static void main(String args[])
{
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
18 Lecture 13- Constructor Overloading
Explanation

• We can pass Object of any class as parameter to a method in java.


• We can access the instance variables of the object passed inside the called
method.
area = r1.length * r1.width
• It is good practice to initialize instance variables of an object before passing
object as parameter to method otherwise it will take default initial values.
• Output :
Area of Rectangle = 200

19 Lecture 13- Constructor Overloading


Example: Passing Instance Variable as an Argument

class Rectangle
{
int length,width;
void area(int length, int width)
{
int areaOfRectangle = length * width;
System.out.println("Area of Rectangle : " + areaOfRectangle);
}
}
class RectangleDemo
{
public static void main(String args[])
{
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
r1.length = 20;
r1.width = 10;
r2.area(r1.length, r1.width);
}
}
20 Lecture 13- Constructor Overloading
Explanation

• We can pass Instance variable of any class as parameter to a method in


java.
• We can access the instance variables of the object passed inside the called
method.
area = length * width
• Output :
Area of Rectangle = 200

21 Lecture 13- Constructor Overloading


Example: Returning object as an Argument

class Rectangle class RetOb


{ {
int length,breadth; public static void main(String args[])
Rectangle(int l,int b) {
{ Rectangle ob1 = new Rectangle(40,50);
length = l; Rectangle ob2;
breadth = b; ob2 = ob1.getRectangleObject();
} System.out.println("ob1.length : " +ob1.length);
Rectangle getRectangleObject() System.out.println("ob1.breadth: " +ob1.breadth);
{ System.out.println("ob2.length : " +ob2.length);
Rectangle rect = new rectangle(10,20); System.out.println("ob2.breadth: " +ob2.breadth);
return rect; }
} }
}

22 Lecture 13- Constructor Overloading


Explanation

• In the program we have called a method getRectangleObject() and the


method creates object of class from which it has been called.
• All objects are dynamically allocated using new, you don’t need to worry
about an object going out-of-scope because the method in which it was
created terminates.
• The object will continue to exist as long as there is a reference to it
somewhere in your program. When there are no references to it, the object
will be reclaimed the next time garbage collection takes place.
• Output :
ob1.length : 40
ob1.breadth: 50
ob2.length : 10
ob2.breadth: 20

23 Lecture 13- Constructor Overloading


Module No 2: Classes and Objects

Lecture No: 14
Recursion
Recursion

• Recursion is the technique of making a function call itself.

• This technique provides a way to break complicated problems down into


simple problems which are easier to solve.

returntype methodname(){
//code to be executed
methodname();//calling same method
}

25 Lecture 14- Recursion


Recursion Example

• Using recursion add a range of numbers together by breaking it down into


the simple task of adding two numbers.

public class Main


{ public static void main(String[] args)
{
int result = sum(10);
System.out.println(result);
}

public static int sum(int k)


{ if (k > 0)
{ return k + sum(k - 1); 10 + sum(9)
} 10 + ( 9 + sum(8) )
else 10 + ( 9 + ( 8 + sum(7) ) )
{ return 0; ...
} 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
} 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
}

26 Lecture 14- Recursion


Excercise

• Write a program to print Factorial of a number using recursion

• Write a program to print Fibonacci series using recursion.

• Write a program to count the digits of a given number using recursion.

27 Lecture 14- Recursion


Subject Name: OOP
Unit No:3
Unit Name: Arrays and String Class

Faculty Name : Mr. Dayanand Dhongade


Index

Lecture 15 – Definition of Array 30

29
Module No 3: Arrays and String Class

Lecture No: 12
Definition of Arrays
Arrays

• Is a collection of similar type of elements


• Syntax: 1-D array
data_type array_name[]=new data_type[size];
data_type[] array_name=new data_type[size];
Or
data_type array_name[];
array_name=new data_type[size];
Eg:-
int A[]=new int[10];
int[] A=new int[10];
Or
int B[];
B=new int[10];

31 Lecture 15 – Definition of Arrays


1-D array initialization

Data_type array_name[]={list of values};

Eg:-
int A[]={10,20,30};

32 Lecture 15 – Definition of Arrays


WAP to calculate sum and average of array elements

import java.util.*; avg=sum/n;


class ArrayAvg
System.out.println(“The sum is
{public static void main(String args[]) “+sum+” and average is “+avg);
{ int n,i,a[];
}
float avg,sum=0.0f;
}
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of
elements:"); Output
n=sc.nextInt(); Enter the number of elements: 5
a=new int[n]; Enter a value:10
Enter a value:20
for(i=0;i<=n-1;i++) Enter a value:30
{ a[i]=sc.nextInt(); Enter a value:40
Enter a value:50
} for(i=0;i<=n-1;i++) The sum is 150 and average is 30.0
{ sum=sum+a[i];
}

33 Lecture 15 – Definition of Arrays


Practice Program

• WAP to search an element in array


• WAP to sort array elements in ascending order

34 Lecture 15 – Definition of Arrays


2-D array

• Syntax
data_type array_name[][]=new data_type[row][col];
data_type[][] array_name=new data_type[row][col];
Or
data_type array_name[][];
array_name=new data_type[row][col];
Eg:-
int A[][]=new int[3][3];
int[][] A=new int[3][3];
Or
int B[][];
B=new int[3][3];

35 Lecture 15 – Definition of Arrays


2-D array initialization

Data_type array_name[][]={{list of values in row1},


{list of values in row2}};

Eg:-
int A[][]={{10,20},{30,40}};

36 Lecture 15 – Definition of Arrays


WAP to display addition of two matrices of size mxn

import java.util.*; System.out.println(“ENTER ARRAY


class MatAdd ELEMENTS FOR A:”);
{public static void main (String args[]) for(i=0;i<m;i++)
{ { for(j=0;j<n;j++)
int A[][],B[][],C[][]; {A[i][j]=sc.nextInt();
int i,j,m,n; }}
Scanner sc=new Scanner(System.in); System.out.println(“ENTER ARRAY
ELEMENTS FOR B:”);
System.out.println(“Enter size of
matrices”); for(i=0;i<m;i++)
m=sc.nextInt(); { for(j=0;j<n;j++)
n=sc.nextInt(); { B[i][j]=sc.nextInt();
A[][]=new int[m][n]; }
B[][]=new int[m][n]; }
C[][]=new int[m][n];

37 Lecture 15 – Definition of Arrays


WAP to display addition of two matrices of size mxn

for(i=0;i<m;i++) for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) for(j=0;j<n;j++)
{ {
C[i][j]=A[i][j]+B[i][j]; System.out.print(C[i][j]+” ”);
} }
} System.out.println();
System.out.println(“Matrix addition }
is\n”); }
}

38 Lecture 15 – Definition of Arrays


Practice Program

• WAP to perform transpose of a matrix


• WAP to perform addition of column elements of a matrix
• WAP to perform addition of diagonal elements of a matrix
• WAP to perform matrix multiplication

39 Lecture 15 – Definition of Arrays


Thank You

You might also like