0% found this document useful (0 votes)
7 views45 pages

Lec 9

Uploaded by

thakurparth270
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)
7 views45 pages

Lec 9

Uploaded by

thakurparth270
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/ 45

OOPS Intro

Class and Object


• As java is an object oriented programming language,
everything should be within the class. A class is nothing
but a collection of variables (also called fields or data) and
methods (functions).
Variables define state and methods define the behavior.
• A class acts as a template (for example - employee) and
object as instance (for example - John, Tom etc.) of that
template.
• Or we can say that class is a collection of objects of similar
types (for example - employee class can have objects like
John, Tom etc (but not tiger, mango etc).
• General Form of Class -
• A class is declared using the keyword "class" followed by the user defined class name.

class Class_Name
{
datatype variable 1;
datatype variable 2;
.
.
datatype variable n;

access_specifier return_type method_Name(parameters...)


{
//body of method
}
.
.
access_specifier return_type method_Name(parameters...)
{
//body of method
}
}

• A class can have any number of variables and methods.


• Variables are called the instance variable because a new copy of these variables is created each time a new
instance (object) of class created.
• No memory is allocated for instance variables in a class.
• Example -

class Employee
{
int id;
String name;
int salary;
float tax;

public void showData()


{
System.out.println(id+" "+name+" "+salary+" "+tax);
}
}

• As we already know class does not exist physically, only objects exist physically. So by
defining Employee class we only create a template and that does not allocate any
memory until we create objects of that class.
• Object of a class can be created as follows -
• Class_Name object_name = new Class_Name();
• So for employee class we can create object as follows
-
• Employee emp1 = new Employee();
• Objects in java are created using the new keyword, It
dynamically allocate memory for object and return a
reference to that object. The reference is nothing but
the address of the object in memory.
• Employee emp1; // declaring object
• emp1 = new Employee();
• // allocate memory and return address of object, that is received in emp1.

• As shown above when object is created a separate copy of instance


variables is created for that object and also the memory is also allocated
for these variables. We can create any number of objects of a given class
and each class will have their own separate copy of instance variables.

• To access the variables and methods associated with an object we use


dot(.) operator.
For example we can assign the value "John" to emp1's name as follows –
• emp1.name="John";
• Example –
class Employee
{
int id;
String name;
int salary;
float tax;
public void showData()
{
System.out.println(id+" "+name+" "+salary+" "+tax);
}
}

public class Demo


{
public static void main(String args[])
{
Employee emp1 = new Employee();
emp1.id = 1; // accessing variables of emp1 object
emp1.name="John";
emp1.salary=20000;
emp1.tax = 200;
emp1.showData(); // accessing method
}
}
• Note - We can define any number of classes in
a single notepad file, but only one class can be
public. And we have to save the file with name
of that class only. So here we have to save the
file with the name 'Demo'.
Data Encapsulation

• Encapsulation means "to put something in a capsule (a wrapper)", so that it


is not directly accessible to outside world.

• For example like medicine capsule, the medicine within capsule wrapper is
not accessible until capsule is dipped in some liquid. I.e. to access medicine
within capsule wrapper we have to follow certain procedure (rules and
regulations).

• In the same way Data Encapsulation means to put data (variables) in some
wrapper so that it is not directly accessible to outsiders. The wrapper here
will be the private access specifiers i.e. declare variables as private so that
they are not accessible outside the class. This process of hiding data from
outsiders is known as Data Hiding. And if any user outside the class wants to
access encapsulated data then he has to follow certain rules and regulations
and these rules and regulations are defined by public methods (getters and
setters methods).
• Example
class Employee
{
private int id;
private String name;
private int salary;

public void setId(int i)


{
if(i<=0)
{
throw new RuntimeException("ID should be greater than zero");
}
else
{
id = i;
}
}

public int getId()


{
return id;
}

public void setName(String n)


{
name = n;
}

public String getName()


{
return name;
}
public void setSalary(int s)
{
if(s<=0)
{
throw new RuntimeException("Salary should be greater than zero");
}
else
{
salary = s;
}
}

public int getSalary()


{
return salary;
}
}

public class Demo


{
public static void main(String args[])
{
Employee emp1 = new Employee();
emp1.setId(1);
// Accessing data using public methods b/c data is encapsulated by making them private.

emp1.setName("Tom");
emp1.setSalary(20000);

System.out.println("Employee details :"+ emp1.getId()+" "+emp1.getName()+" " + emp1.getSalary());


}
}
• Output -
• Employee details :1 Tom 20000

In the above program we declare all data (id, name, salary) of the
Employee class as private so that anyone outside the class should not be
able to access it directly. This process of wrapping the data in private
access specifier is known as Data Encapsulation.

If someone wants to access this encapsulated data then he has to follow


certain rules and regulations, and we have declared these rules and
regulations by defining methods (for example if user enter id of
employee less than one then a Runtime Exception object will be thrown
showing the message 'ID should be greater than zero' and programs
terminates there).

Right now, you do not need to be worried about what Exception is,You
will learn it later.For now just consider that it will stop program execution
and show the message whatever you entered in double quotes.).
• Benefit of Data Encapsulation -
• So now the question arises why we encapsulate
data, and what is the benefit of doing this?
By making data encapsulated, we ensure that
anyone outside the class should not be able to
access the data, if he passes some anonymous
values for data for example we know that
Employee id can never be 0 or negative similarly
salary can also never be zero or negative. So if
user ever passes some negative values or zero for
these data then he will not be able to access them
and a Runtime Exception will be thrown.
Constructor

• Each object we created must be initialized to some value. We can do this in two
ways -

• 1 - We can initialize objects by using dot operator -

emp1.id = 1;
emp1.name="Tom";
• 2 - Secondly we can initialize objects by using methods -
emp1.setId(1);
emp1.setName("Tom");
• But the initialization of objects is so common that Java enables objects to
initialize themselves when they are created.

• This automatic initialization is done through the use of Constructor.


• Constructors are similar to methods and have
the following features -
1- They have the same name as class name.
2- They do not have any return type, not even
void.
3- They run automatically as a new object is
created and run only once for any object.
4- If we do not explicitly create any
constructor in class than a default constructor
is automatically created by Java run time
system.
• Example 1-

class Employee
{
public void a()
{
System.out.println("AAA");
}
public void b()
{
System.out.println("BBB");
}
public Employee() // Constructor
{
System.out.println("You are in Constructor");
}
}

public class Demo


{
public static void main(String args[])
{
Employee emp1 = new Employee(); // Calling constructor

//emp1.Employee(); Error we cannot call constructors like simple methods.

emp1.a();
emp1.b();
}
}

Output -
You are in Constructor
AAA
BBB
• Program Description -
• Note that constructor :
public Employee()
{
System.out.println("Constructor");
}
• Have the same name as class name and also do not have any return type.

• As we create the object by writing the code: Employee emp1 = new


Employee(); compiler will search for a Employee() constructor in
Employee class and run it automatically. That is why 'You are in
Constructor' is printed first .

• Also note that constructor runs only once for any object when we create
that object, we cannot call them multiple times like java methods.
• Types of Java Constructor -
• Constructor is of two types -

• 1- Constructor without parameter (Default Constructor) - If a constructor does not have any
parameter than it is called Default Constructor, as constructor created in last example.

• If you do not define any constructor explicitly, a default constructor is automatically built by
java run time system.

• For example -
class Employee
{
}
• Even though we have not define anything within the class but compiler will automatically
generate a default constructor within the class like this -
public Employee()
{
}
• Note - A default constructor initializes all data members (variables) of the class to their
default values.
• 2 - Constructor with parameter
(Parameterized Constructor) - If a constructor
has one or more parameters then it is called
parameterized constructor.

• For example -
public Employee(int i, String n)
{
//Statements;
}
Example -

class Employee
{
int id;
String name;
public void input()
{
id = Integer.parseInt(System.console().readLine("Enter ID"));
name = System.console().readLine("Enter name");
}
public void disp()
{
System.out.println(id+ " " + name);
}

public Employee(int i, String n) // parameterized constructor


{
id = i;
name = n;
}
}

public class Demo


{
public static void main(String args[])
{
Employee emp1 = new Employee(1, "Tom");
emp1.disp();
}
}
• Output-
• 1 Tom
• Note that when the code Employee emp1 = new Employee(1, "Tom"); will
execute, compiler will look for a constructor in Employee class that contain
two parameters, where first parameters is of int type and second is of
string type, when it finds a match that matching constructor will executes.
So here it will find a match with the only constructor we have, and execute
it. It causes id and name of emp1 to be set at the value i (i.e. 1 in this case)
and n (i.e. 'Tom in this case').
• Always remember that if we define any constructor
explicitly then default constructor does not built by
compiler. So in the above example there will be no
default constructor built by complier. So if we try to
execute the following code

• Employee emp1 = new Employee();

• There will be error. Because now compiler will look


for a constructor in Employee class that does not
have any parameter but it will not find any such
constructor. So there will be error.
• Constructor Overloading -
• If we define more than one constructor within
a class then it is called constructor
overloading.
• A class can have any number of constructor as
long as their parameter declaration is different
i.e. either the number of parameter or data
type of parameter should be different.
• Example -

class Employee
{
int id;
String name;
public void input()
{
id = Integer.parseInt(System.console().readLine("Enter ID"));
name = System.console().readLine("Enter name");
}
public void disp()
{
System.out.println(id+ " " + name);
}

public Employee() // Constructor 1


{
}

public Employee(int i) // Constructor 2


{
id = i;
}
public Employee(String n) // Constructor 3
{
name = n;
}
public Employee(int i, String n) // Constructor 4
{
id = i;
name = n;
}
public Employee(String n, int i) // Constructor 5
{
id = i;
name = n;
}
}
public class Demo
{
public static void main(String args[])
{
Employee emp1 = new Employee();
Employee emp2 = new Employee(1);
Employee emp3 = new Employee("Tom");
Employee emp4 = new Employee(1, "Tom");
emp1.disp();
emp2.disp();
emp3.disp();
emp4.disp();
}
}
• Output -
• 0 null
• 1 null
• 0 Tom
• 1 Tom
• Here we have defined 5 constructors, Constructor 1 does not have any
parameter, Constructor 2 has 1 parameter of int type, Constructor 3 also
has 1 parameter but it is of String type, and so on.

• When the code Employee emp1 = new Employee(); gets executed, it will
cause the compiler to look for a constructor that is not having any
parameter, so Constructor 1 will gets executed and initialize data fields of
emp1 to their default value (i.e. 0 for int and null for String)
• Note the default value of object type is null.

• The next line Employee emp2 = new Employee(1);


will cause the compiler to look for a constructor that
is having only one parameter of int type , so
Constructor 2 will gets executed and initialize id to 1
and name to null.
• The next line
• Employee emp3 = new Employee("Tom");
• will cause the compiler to look for a
constructor that is having only one parameter
of String type , so Constructor 3 will gets
executed and initialize id to 0 (default value of
int) and name to "Tom".
• The next line
• Employee emp4 = new Employee(1,"Tom");
will cause the compiler to look for a
constructor that is two parameters 1st is of int
type and 2nd is of String type , so Constructor
4 will gets executed and initialize id to 1 and
name to "Tom".
• Copy Constructor -
• This constructor is used to create a copy of object.
Example -

class Employee
{
int id;
String name;

public void input()


{
id = Integer.parseInt(System.console().readLine("Enter ID"));
name = System.console().readLine("Enter name");
}
public void disp()
{
System.out.println(id+ " " + name);
}

public Employee(int i, String n)


{
id = i;
name = n;
}
public Employee(Employee emp) // Copy Constructor
{
id = emp.id;
name = emp.name;
}
}
public class Demo
{
public static void main(String args[])
{
Employee emp1 = new Employee(1, "Tom");
emp1.disp();
Employee emp2 = new Employee(emp1);
emp2.disp();
}
}

Output -
1 Tom
1 Tom
• When the code Employee emp1 = new
Employee(1, "Tom"); gets executed, it will call
the constructor and set emp1 id to 1 and
name to 'Tom'.

• Next line emp.disp(); will call disp() method to


display id and name of emp1 object.
• the next line Employee emp2 = new
Employee(emp1); will call the second
constructor and the value of emp in
constructor will be equal to emp1 i.e. emp now
will refer to same object as emp1.

• When constructor gets executed it will set


emp2 id and name to emp.id (i.e. 1) and
emp.name (i.e. Tom). So created exact copy
emp1. That is why it is called Copy Constructor.
• The next line will display the id and name of
emp2.
• Chaining Of Constructors -
• We can also chain constructor to each other
using this(). While chaining you should remember
the following rules -
1- One constructor can chain only one constructor.
2- this() should be the first statement within
constructor.
3- It should not form a cycle while chaining. i.e. -
Example -

class Employee
{
int id;
String name;

public void input()


{
id = Integer.parseInt(System.console().readLine("Enter ID"));
name = System.console().readLine("Enter name");
}
public void disp()
{
System.out.println(id+ " " + name);
}

public Employee(int i) // Constructor 1


{
id = i;
}
public Employee(String n) // Constructor 2
{
name = n;
}

public Employee(int i, String n) // Constructor 3


{
this(i); // chaining to constructor 1
name = n;
}

public Employee(String n, int i) // Constructor 4


{
this(i,n); // chaining to constructor 3
}
public Employee(Employee emp) // Constructor 5
{
this(emp.name); // chaining to constructor 2
id = emp.id;
}
}
public class Demo
{
public static void main(String args[])
{
Employee emp1 = new Employee("John", 2);
emp1.disp();
}
}

• When the code Employee emp1 = new Employee("John", 2); gets executed , It will call to
constructor 4 and the statement this(i,n) will call to a constructor that have first
parameter of int type and second parameter of String type, So it will call to constructor
3.
• Constructor 3 contain the 1st statement this(i) , it will call to a constructor that contain
only 1 parameter of int type so constructor 1 will be executed and set the id of emp1 to
1.
• Then it will come back to constructor 3 that will set the name of emp1 to 'John' and
finally it come back to constructor 4.
• The next line emp1.disp(); will display id and name of emp1.
• 'this' keyword -
• this means 'object of current class'. It refers to the current object.
'this' keyword is normally used to differentiate between local and
class variables within a method. When local variables within method
have the same name as class variables then local variables hides the
class variables. In that case this keyword is used to refer class
variables.
For example - consider the Constructor 4 of previous example -
public Employee(int id, String name)
{
this.id = id;
this.name = name;
}
Here this.id refers to object's id and id refers to method's id. Similarly
this.name refers to object name and name refers to method name.
Method Overloading (Function
Overloading) -
• In java it is possible to have multiple methods with the same
name in a class as long as their parameter declarations are
different i.e. either the number of parameters or data types of
parameters are different. In this case methods are said to be
overloaded and process is referred as method overloading.
This is one of the ways Java supports the concept of
Polymorphism.
• When an overloaded method is called, Compiler checks for
the number and data types of parameters to determine which
overloaded method to call.
Note - Always remember that there is no method overloading
on the basis of return type of methods.
class Test
{
public int sum(int a) // version 1
{
return (a+a);
}
public int sum(int a, int b) // version 2
{
return (a+b);
}
public double sum(double a) // version 3
{
return (a+a);
}
public double sum(double a, double b) // version 4
{
return (a+b);
}
}

public class Demo


{
public static void main(String[] args)
{
Test t1 = new Test();
int sum1 = t1.sum(1); // call to version1
int sum2 = t1.sum(1,2); // call to version2
double sum3 = t1.sum(10.5); // call to version3
double sum4 = t1.sum(11.5, 12.5); // call to version4
System.out.println(sum1+" "+sum2+" "+sum3+" "+sum4);
}
}
• Here we have overloaded a method named sum four times. The first version contains
an int parameter, second version contains two parameters of int type, third version
contains single double parameter and fourth version contains two double type
parameters.
The return type of overloaded method can be same or different, because there is no
overloading on the basis of return type.
When the code int sum1 = t1.sum(1); gets executed, compiler looks for the version
of sum method, that contain one parameter of int type so version 1 will gets
executed and return the result in sum1 variable.
Similarly when int sum2 = t1.sum(1,2); gets executed, compiler looks for that version
of sum method that contain two parameters of int type so second version will gets
executed and return the result in sum2 variable and so on.
It is clear from the above example when an object call to an overloaded method,
compiler looks for a match between the values used to call the method and method
parameters.
But there can be case when compiler does not find exact match. In that case java
automatically performs type conversion to call the method and this conversion is
only possible if method parameter data type is larger in size compared to arguments
(values) used to call the method. This conversion is only take place when compiler
does not find exact match.
For Example -

class Test
{
public int sum(int a, int b) // version 1
{
return (a+b);
}
public double sum(double a) // version 2
{
return (a+a);
}
}

public class Demo


{
public static void main(String[] args)
{
Test t1 = new Test();
int sum1 = t1.sum(1, 2); // call to version1
double sum2 = t1.sum(10); // call to version2
double sum3 = t1.sum(10.5); // call to version2
System.out.println(sum1+" "+sum2+" "+sum3);
}
}

You might also like