object orineted programming
TRANSCRIPT
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 1/37
Recap of day 1
y Object Oriented Programmingy
Classy Abstraction
y Encapsulationy Polymorphismy
OO Analysisy Access Modifiersy Creating Objectsy this Reference
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 2/37
ConstructorsConstructorsCommunication Team
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 3/37
Constructors (1/5)Constructors (1/5)
y A constructor is a special method that is
called to create a new object
y A constructor method
will have the same name as that of the class will not have any return type, not even void
PolicyHolder policyHolder = new PolicyHolder();
Calling theconstructor
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 4/37
Constructors (2/5)Constructors (2/5)
y The coder can write a constructor in a class, if required
y If a user defined constructor is available, it iscalled just after the memory is allocated for theobject
y If no user defined constructor is provided for aclass, the implicit constructor initializes the
member variables to its default values numeric data types are set to 0 char data types are set to null character(µ\0¶) boolean data types are set to false
reference variables are set to null
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 5/37
Constructors (3/5)Constructors (3/5)
public class PolicyHolder{
//Data Members
public PolicyHolder(){
bonus = 100;
}
//Other Methods}
UserdefinedConstructor
PolicyHolder policyHolder = new PolicyHolder();//policyHolder.bonus is initialized to 100
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 6/37
Method Overloading (1/3)Method Overloading (1/3)
y Two or more methods in a Java class can
have the same name, if their argumentlists are different
y Argument list could differ in No of parameters
Data type of parameters Sequence of parameters
y This feature is known as MethodOverloading
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 7/37
Method Overloading (2/3)Method Overloading (2/3)
y Calls to overloaded methods will be resolved duringcompile time Static Polymorphism
void print(int i){
System.out.println(i);
}void print(double d){
System.out.println(d);
}
void print(char c){
System.out.println(c);
}
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 8/37
Method Overloading (3/3)Method Overloading (3/3)
void add (int a, int b)
void add (int a, float b)
void add (float a, int b)
void add (int a, int b, float c)
v
oid add (int a, float b)int add (int a, float b)
Overloadingmethod
Not Overloading
Compile error
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 9/37
Overloading the ConstructorsOverloading the Constructors
Just like other methods, constructors also
can be overloaded
The constructor without any parameter is
called a default constructor
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 10/37
Constructors (5/5)Constructors (5/5)
public class PolicyHolder{//Data Memberspublic PolicyHolder(){
bonus = 100;}public PolicyHolder(int policyNo, double
bonus){this.policyNo = policyNo;this.bonus = bonus;
}//Other Methods
}
y PolicyHolder policyHolder1 = new PolicyHolder();
y //policyHolder1.policyNo is 0 and bonus is 100
y PolicyHolder policyHolder = new PolicyHolder(1, 200);y //policyHolder1.policyNo is 1 and bonus is 200
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 11/37
Memory Allocation (2/2)Memory Allocation (2/2)
public class PolicyHolder{private int policyNo;private double bonus;//Other Data Memberspublic void sample(int x){
int y;//More Statements
}//More Methods
}class Test{public static void main(String [] args){
PolicyHolder policyHolder;policyHolder = new PolicyHolder();
}}
Data members of theclass are stored in theheap along with theobject. Their lifetimedepends on the lifetime of
the object
Local variables x and yare stored in the Stack
Local variablepolicyHolder is storedin the Stack
Dynamic objects will bestored in the heap
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 12/37
Lifetime of objects (1 of 2)Lifetime of objects (1 of 2)
y Policy policy1 = new Policy();
y
Policy policy2 = new Policy();y The two Policy objects are now living
y on the heap References: 2
Objects: 2y Policy policy3 = policy2;
References: 3
Objects: 2
2policyNo
bonus
1
policyNobonus
heap
policy1
policy2
2policyNobonus
1
policyNobonus
policy1
policy2
policy3
heap
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 13/37
Lifetime of objects (2 of 2)Lifetime of objects (2 of 2)
y policy3 = policy1;
References: 3
Objects: 2y policy2 = null;
Active References: 2
null references: 1
Reachable Objects: 1
Abandoned objects: 1
2policyNo
bonus
1policyNo
bonus
heap
policy1
policy2
policy3
2policyNo
bonus
1policyNo
bonus
policy1
policy2
policy3
heap
Null
reference
This object can begarbage collected
(Can be Removedfrom memory)
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 14/37
Garbage Collection
y In programming languages like C and C++, theprogrammer has to de-allocate all dynamic memory
y An object that is not referred by any reference variable willbe removed from the memory by the garbage collector
Automatic Garbage Collection
If a reference variable is declared within a function, thereference is invalidated soon as the function call ends
Programmer can explicitly set the reference variable tonull to indicate that the referred object is no longer inuse
y Primitive types are not objects and they cannot beassigned null
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 15/37
The static keyword
y The static keyword can be used in 3
scenarios: For class variables
For methods
For a block of code
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 16/37
Static Data Members
y Static data is a data that is common to the entire class
y Assume that the class PolicyHolder wants to keep track of the
total number of Policy Holders The data common to the entire class
An int data member total should be declared as static
A single copy of total will be shared by all instances of the class
public class PolicyHolder{ private int policyNo;
private double bonus;
private static int total;
//Other Data Members and Methods
}
The static variable is initialized to 0,
ONLY when the class is first loaded,NOT each time a new instance is made
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 17/37
Static Methods (1/3)
y Static method is a method that is
common to the entire classy Consider a method getTotal() in the class
PolicyHolder that returns the value of thestatic data member total
It is more logical to think of this method as amethod of the entire class rather than that of an object
The method getTotal() is declared as static
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 18/37
Static Methods (2/3)
public class PolicyHolder{
private int policyNo;
private double bonus;
private static int total;
//Other Data Members and Methods
public PolicyHolder(){
++total;
//Other Statements
}
public static int getTotal(){
return total;}
}
Each time the constructor isinvoked and an object gets created,
the static variable total will be
incremented thus keeping a count
of the total no of PolicyHolder
objects created
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 19/37
Static Methods (3/3)
y Static methods are invoked using the syntax <ClassName.MethodName>
y Static methods can access only other static data and methods
System.out.println(PolicyHolder.getTotal());
//Prints 0
//A static method can be invoked without creating an object
PolicyHolder policyHolder1 = new PolicyHolder ();
System.out.println(PolicyHolder.getTotal());//Prints 1
PolicyHolder policyHolder2 = new PolicyHolder ();
System.out.println(PolicyHolder.getTotal());
//Prints 2
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 20/37
The Static Block
y The static block is a block of statement inside a Java class thatwill be executed when a class is first loaded
A static block helps to initialize the static data members just like constructors help to initialize instance members
class Test{
static{
//Code goes here
}
}
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 21/37
Strings in Java (1/3)
y String is a system defined class in Java
y
Declaring ³Hello World´ in code will createan object of type string with data ³HelloWorld´ and returns a reference to it.
System.out.println(³Hello World´);
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 22/37
Strings in Java (2/3)
y A String object can be created without the new operator
Declaring ³Hello World´ in code will create an object of typestring with data ³Hello World´ and returns a reference to it.
String s = ³Java´;
String s1 = ³Hello´;
String s2 = ³World´;
String s3 = s1 + s2; //s3 will contain ³HelloWorld´
int a = 20;
System.out.println(³The value of a is ´ + a);
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 23/37
Command Line Arguments
y The main method takes an array of String as theparameter
y This array contains the command line arguments that arepassed when the program is invoked
> java Sample Hello Welcome Ok
Hello, Welcome and Ok will be passed as an array of 3
elements to the main method of the class Sample
class Sample{
public static void main(String [] args){
for(int i = 0; i < args.length; ++i)
System.out.println(args[i]);
}
}
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 24/37
A Complete Java Program - Revisited
y
The main method is public so that it can be accessed outside the class is static so that it can be invoked without creating any
objects is void and does not return anything can take command line arguments as an array of String
public class HelloWorld{
public static void main(String [] args){
System.out.println(³Hello World!´);
}
}
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 25/37
Can you answer these questions?
y What is a this reference?
y
What are Constructors?y What is method overloading?
y What is Automatic Garbage Collection inJava?
y What are the uses of the keyword static?
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 26/37
Inheritance (1/3)
y Assume that we require a class TermInsurancePolicy
Needs all the features of the class Policy
TermInsurancePolicy will have a pre defined number of years before they expire
Needs to add an extra data called term and relevantmethods
The keyword extends is used in Java to inherit a subclass from a super class
public class TermInsurancePolicy extends Policy{
//Data Members and Methods
}
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 27/37
Inheritance (2/3)
y The class Policy is known as the super class
parent class
y The class TermInsurancePolicy is knownas
sub class derived class
child class
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 28/37
Policy [Parent Class]
y public class Policy{y private double premium;y private double maturityValue;y //Other Datay public void setPremium(double premium){y this.premium = premium;y }y public double getPremium(){return premium;}y public void setMaturityValue(double maturityValue){y
this.maturityValue = maturityValue;y }y public double getMaturityValue(){return
maturityValue;}y //Other Methodsy }
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 29/37
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 30/37
The protected Access
y The method getBenefit() needs to access the datamembers premium and maturityValue of the class Policy
y A class member that has the protected access specifier canbe accessed by the sub classes also
maturityValue and premium should be declared asprotected
public class Policy{
protected double premium;
protected double maturityValue;
//Other Members
}
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 31/37
Creating the sub class Object
y A TermInsurancePolicy object can invoke all the publicmethods of the class Policy and those that are newly addedin TermInsurancePolicy
y Thus code reusability is achieved
TermInsurancePolicy policy = new TermInsurancePolicy();
policy.setPremium(100);
policy.setMaturityValue(5000);
policy.setTerm(36);
System.out.println(policy.getBenefit());
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 32/37
Inheritance
+setPremium(in premium : double) : void+getPremium() : double
+setMaturityValue(in maturityValue : double) : void
+getMaturityValue(in Amount : double) : void
-premium : double
-maturityValue : double
Policy
+setTerm(in term : int) : void
+getTerm() : int
+getBenifit() : double
-term : int
TermInsurancePolicy
Note: Inheritance is represented by a triangle head arrow in UMLClass diagrams
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 33/37
Multi-Level Inheritance
y A class can be further inherited from a
derived class
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 34/37
Multiple Inheritance
y Concept of a class inheriting from morethan one base class A Hybrid car can inherit from FuelCar andBatteryCar
Multiple inheritance is rarely used because of the complexities it brings in
y Modern OO languages like Java and C#don¶t support Multiple Inheritance
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 35/37
More on Inheritance
y Any number of sub classes can be createdfrom a base class
y Consider a class EndowmentPolicy EndowmentPolicy is a Policy; EndowmentPolicyis extended from Policy
Extra data members and methods are added
public class EndowmentPolicy extends Policy{
//Data Members and Methods
}
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 36/37
Can you answer these questions?
y What is a protected access?
y
What is multilevel inheritance?
8/7/2019 Object Orineted Programming
http://slidepdf.com/reader/full/object-orineted-programming 37/37
Thank You