0% found this document useful (0 votes)
16 views34 pages

Week 3-LectureA OOPs

Uploaded by

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

Week 3-LectureA OOPs

Uploaded by

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

Constructor

overloading, constructor
chaining, and copy
constructor
(Java)
Contents
2

 Recap of previous lecture


 Function overloading
 Constructor overloading
 Constructor chaining
 Copy constructor
 References
 Next lecture
Recap of previous lecture/week
3

• Default – No keyword required


• Public
• Private
• Protected

• Default constructor
• No-argument constructor
• Parametrized constructor
Function overloading
4

First understand or revise the concept of function overloading

• Method Overloading is a
feature that allows a class to
have more than one method
having the same name, if
their argument lists are
different.

• It is similar to constructor
overloading in Java, that
allows a class to have more
than one constructor having
different argument lists.
Constructor overloading
5

• Constructor can be overloaded

• An overloaded constructor provides multiple ways to set up a new object

• Complier differentiates which constructor is to be called depending on the


signature (type, sequence, number of arguments).

• When we construct an object, the complier decides which constructor to invoke


according to the type of the actual parameter.
Constructor overloading syntax
6
Constructor overloading example
7
Constructor chaining
8

• Constructor Chaining is the process of calling one constructor of a class from


another constructor of the same class or another class using the current object of
the class.

• There are two ways by which we can use constructor chaining in Java. These ways
depend on whether we are using it in the same class or the different class.

Using this keyword


Using the super keyword (will discuss later)
Constructor chaining example
9

package ThisExample; //Parameterized constructor


class Example Example(int n)
{ {
//non-parametrized constructor //calling parametrized constructor
Example() this(4.5);
{ System.out.println("Inside Parameterized“+n);
System.out.println("Inside non-parametrized "); }
} }
//Parameterized constructor
Example(double x)
{ package ThisExample;
//calling non-parametrized constructor public class ThisExample
this(); {
System.out.println("Inside Parameterized“+x); public static void main(String arg[])
} {
//calling the parameterized constructor
Example obj = new Example(15);
}
}
Copy constructor
10

• A Copy Constructor in Java is a special type of constructor that is used to create a


new object using the existing object of a class that we have created previously.

• It creates a new object by initializing the object with the instance of the same
class.

• The Java Copy Constructor provides a copy of the specified object by taking the
argument as the existing object of the same class.

• Java does not implicitly provide the facility of a Copy constructor as in C language.

• But, we can define it by copying the values of one object to another object.
Creating a Copy Constructor in Java
11

• To create a copy constructor in java, we need to first declare a constructor that


takes an object of the same type as a parameter. For example:

public class Student


{
private int roll ;
private String name;
// Declaring a copy constructor by passing the parameter as the class
public Student( Student student )
{}
}
Creating a Copy Constructor in Java
12

• After declaring a copy constructor, we need to copy each field of the input object
of the class into the new object. For example:

public class Student


{
private int roll;
private String name;
// Copying each field of the existing object into the newly created object
public Student( Student student )
{
this.id = student.roll;
this.name = student.name;
}
}
Copy Constructor example
13

package Xyz;
public class Student
{
private int roll;
private String name;
//constructor to initialize roll number and name of the student
Student(int rollNo, String sName)
{
//method to return roll number
roll = rollNo;
int printRoll()
name = sName;
{
}
return roll;
//copy constructor
}
Student(Student student)
//Method to return name of the student
{
String printName()
System.out.println("\n---Copy Constructor Invoked---");
{
roll = student.roll;
return name;
name = student.name;
}
}
}
Copy Constructor example
14

//class to create student object and print roll number and name of the student
package Xyz;
public class Xyz
{
public static void main(String[] args)
{
Student student1 = new Student(101, “ali");
System.out.println("Roll number of the first student: "+ student1.printRoll());
System.out.println("Name of the first student: "+ student1.printName());

//passing the parameter to the copy constructor


Student student2 = new Student(student1);
System.out.println("\nRoll number of the second student: "+ student2.printRoll());
System.out.println("Name of the second student: "+ student2.printName());
} Roll number of the first student: 101
} Name of the first student: Ali
—Copy Constructor Invoked—
Roll number of the second student: 101
Name of the second student: Ali
Creating a Copy Constructor in Java
15

• From the previous code, we created a shallow copy of the object. It will work fine
as we are using the immutable and primitive types, i.e int and String.

• But what if we have mutable types in our code?

• What is deep copy?

• What are the differences between shallow and deep copy?

• What are the advantages of copy constructor?

• What are the uses of this keyword?


https://www.youtube.com/watch?v=q6hnM2_vO-8
Static data, method,
block and inner classes
(Java)
Contents
17

 Recap of previous lecture


 Static data
 Static method
 Static block
 Inner classes
 Anonymous object
 References
 Next lecture
Recap of previous lecture
18

• Constructor overloading

• Constructor chaining

• Copy constructor
Static data
19

• If you declare any variable as static, it is known as a static variable.

• The static variable can be used to refer to the common property of all objects, for
example, the company name of employees, college name of students, etc.

• The static variable gets memory only once in the class area at the time of class
loading.

• It makes your program memory efficient (i.e., it saves memory).


Static data
20

class Student{
int regno;
String name;
String uni=“CUI";
}
Suppose there are 500 students in my university, now all instance data members will get
memory each time when the object is created.

All students have its unique regno and name, so instance data member is good in such case.
Here, “uni" refers to the common property of all objects.

If we make it static, this field will get the memory only once.

Java static property is shared to all objects.


Static data example
21

//Java Program to demonstrate the use of static variable


class Student
{
private int regno;//instance variable
private String name;
static String uni =“CIIT";//static variable
//Test class to show the values of objects
//constructor public class TestStaticVariable1
Student(int r, String n) {
{ public static void main(String args[])
regno = r; {
name = n; Student s1 = new Student(111,“ali");
} Student s2 = new Student(222,“kamran");
//method to display the values
//we can change the university of all objects
void display ()
{
by the single line of code
System.out.println(regno+" "+name+" "+uni); //Student.uni=“CUI";
} s1.display();
} s2.display();
}
}
Static method
22

• If you apply static keyword with any method, it is known as static method.

• A static method belongs to the class rather than the object of a class.

• A static method can be invoked without the need for creating an instance of a
class.

• A static method can access static data member and can change the value of it.
Static method
23

There are two main restrictions for the static method. They are:

• The static method can not use non static data member or call non-static method
directly.
• this and super cannot be used in static context.
class A
{
int a=40;//non static

public static void main(String args[])


{
System.out.println(a);
}
}
Static method example
24

//Java Program to demonstrate the use of a static method.


class Student
{ //Test class to create and display the values of object
int regno; public class TestStaticMethod
String name; {
static String uni = “CIIT"; public static void main(String args[])
//static method to change the value of static variable {
static void change() Student.change();//calling change method
{ college = “CUI"; } //creating objects
//constructor to initialize the variable Student s1 = new Student(111,“ali");
Student(int r, String n) Student s2 = new Student(222,“kamran");
{ regno = r; Student s3 = new Student(333,“raza");
name = n;} //calling display method
//method to display values s1.display();
void display() s2.display();
{System.out.println(regno+" "+name+" "+uni);} s3.display();
} }
}
Static block
25

• Is used to initialize the static data member.

• It is executed before the main method at the time of class loading.

class A2
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
Output: System.out.println("Hello main");
static block is invoked }
Hello main }
Inner classes
26

• In Java, it is also possible to nest classes (a class within a class).

• The purpose of nested classes is to group classes that belong together, which
makes your code more readable and maintainable.

• To access the inner class, create an object of the outer class, and then create an
object of the inner class:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Using reference of outer object you are creating object for Iner class, because Iner is
part of Outer class.
Inner classes example
27

class OuterClass
{
int x = 10;

class InnerClass
{
int y = 5;
}
}
public class MyMainClass
{
public static void main(String[] args)
{
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
} // Outputs 15 (5 + 10)
}
Private inner classes and example
28

• Unlike a "regular" class, an inner class can be private or protected.

• If you don't want outside objects to access the inner class, declare the class as
private class OuterClass
{
int x = 10;
private class InnerClass
{int y = 5;}
}
public class MyMainClass
{
public static void main(String[] args)
{
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
} MyMainClass.java:12: error:
Static inner/nested class
29

• A static class i.e. created inside a class is called static nested class in java.

• It cannot access non-static data members and methods.

• An inner class can also be static, which means that you can access it without
creating an object of the outer class:

• It can be accessed by outer class name.

• It can access static data members of outer class including private.

• Static nested class cannot access non-static (instance) data member or method.
Static inner/nested class example
30

class TestOuter1
{
static int data=30; A static inner class is a nested class
which is a static member of the outer
static class Inner
class.
{
void msg() It can be accessed without instantiating
the outer class, using other static
{System.out.println("data is "+data);}
members.
}
public static void main(String args[]) Just like static members, a static nested
class does not have access to the
{
instance variables and methods of the
TestOuter1.Inner obj=new TestOuter1.Inner(); outer class.
obj.msg();
}
}
Static nested class example
31

class TestOuter1
{
static int data=30;
In this example, you need to
static class Inner create the instance of static nested
{ class because it has instance
void msg() method msg().

{System.out.println("data is "+data);} But you don't need to create the


} object of Outer class because
public static void main(String args[]) nested class is static and static
properties, methods or classes can
{ be accessed without object.
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Anonymous object
32

Anonymous simply means nameless. An object which has no reference is


known as an anonymous object.

It can be used at the time of object creation only.

If you have to use an object only once, an anonymous object is a good


approach. For example:

new Calculation();//anonymous object


new Calculation().fact(5);
1.Calculation c=new Calculation();
2.c.fact(5);
Anonymous object example
33

class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[])
{
new Calculation().fact(5);//calling method with anonymous object
}
}
34

THANK YOU

You might also like