Recap of day 1 : Recap of day 1 Object Oriented Programming
Class
Abstraction
Encapsulation
Polymorphism
OO Analysis
Access Modifiers
Creating Objects
this Reference
Constructors : Constructors Communication Team
Constructors (1/5) : Constructors (1/5) A constructor is a special method that is called to create a new object
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 the constructor
Constructors (2/5) : Constructors (2/5) The coder can write a constructor in a class, if required
If a user defined constructor is available, it is called just after the memory is allocated for the object
If no user defined constructor is provided for a class, 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
Constructors (3/5) : Constructors (3/5) public class PolicyHolder{
//Data Members
public PolicyHolder(){
bonus = 100;
}
//Other Methods
} User defined Constructor PolicyHolder policyHolder = new PolicyHolder();
//policyHolder.bonus is initialized to 100
Method Overloading (1/3) : Method Overloading (1/3) Two or more methods in a Java class can have the same name, if their argument lists are different
Argument list could differ in
No of parameters
Data type of parameters
Sequence of parameters
This feature is known as Method Overloading
Method Overloading (2/3) : Method Overloading (2/3) Calls to overloaded methods will be resolved during compile 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);
}
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)
void add (int a, float b)
int add (int a, float b) Overloading method Not Overloading
Compile error
Overloading the Constructors : Overloading the Constructors Just like other methods, constructors also can be overloaded
The constructor without any parameter is called a default constructor
Constructors (5/5) : Constructors (5/5) public class PolicyHolder{
//Data Members
public PolicyHolder(){
bonus = 100;
}
public PolicyHolder(int policyNo, double bonus){
this.policyNo = policyNo;
this.bonus = bonus;
}
//Other Methods
} PolicyHolder policyHolder1 = new PolicyHolder();
//policyHolder1.policyNo is 0 and bonus is 100
PolicyHolder policyHolder = new PolicyHolder(1, 200);
//policyHolder1.policyNo is 1 and bonus is 200
Memory Allocation (2/2) : Memory Allocation (2/2) public class PolicyHolder{
private int policyNo;
private double bonus;
//Other Data Members
public 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 the class are stored in the heap along with the object. Their lifetime depends on the lifetime of the object Local variables x and y are stored in the Stack Local variable policyHolder is stored in the Stack Dynamic objects will be stored in the heap
Lifetime of objects (1 of 2) : Lifetime of objects (1 of 2) Policy policy1 = new Policy();
Policy policy2 = new Policy();
The two Policy objects are now living
on the heap
References: 2
Objects: 2
Policy policy3 = policy2;
References: 3
Objects: 2 2
policyNo
bonus 1
policyNo
bonus policy1 policy2 policy3 heap
Lifetime of objects (2 of 2) : Lifetime of objects (2 of 2) policy3 = policy1;
References: 3
Objects: 2
policy2 = null;
Active References: 2
null references: 1
Reachable Objects: 1
Abandoned objects: 1 2
policyNo
bonus 1
policyNo
bonus heap policy1 policy2 policy3 2
policyNo
bonus 1
policyNo
bonus policy1 policy2 policy3 heap Null reference This object can be garbage collected (Can be Removed from memory)
Garbage Collection : Garbage Collection In programming languages like C and C++, the programmer has to de-allocate all dynamic memory
An object that is not referred by any reference variable will be removed from the memory by the garbage collector
Automatic Garbage Collection
If a reference variable is declared within a function, the reference is invalidated soon as the function call ends
Programmer can explicitly set the reference variable to null to indicate that the referred object is no longer in use
Primitive types are not objects and they cannot be assigned null
The static keyword : The static keyword The static keyword can be used in 3 scenarios:
For class variables
For methods
For a block of code
Static Data Members : Static Data Members Static data is a data that is common to the entire class
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
Static Methods (1/3) : Static Methods (1/3) Static method is a method that is common to the entire class
Consider a method getTotal() in the class PolicyHolder that returns the value of the static data member total
It is more logical to think of this method as a method of the entire class rather than that of an object
The method getTotal() is declared as static
Static Methods (2/3) : 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 is invoked and an object gets created, the static variable total will be incremented thus keeping a count of the total no of PolicyHolder objects created
Static Methods (3/3) : Static Methods (3/3) Static methods are invoked using the syntax
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
The Static Block : The Static Block The static block is a block of statement inside a Java class that will 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
}
}
Strings in Java (1/3) : Strings in Java (1/3) String is a system defined class in Java
Declaring “Hello World” in code will create an object of type string with data “Hello World” and returns a reference to it. System.out.println(“Hello World”);
Strings in Java (2/3) : Strings in Java (2/3) A String object can be created without the new operator
Declaring “Hello World” in code will create an object of type string 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);
Command Line Arguments : Command Line Arguments The main method takes an array of String as the parameter
This array contains the command line arguments that are passed 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]);
}
}
A Complete Java Program - Revisited : A Complete Java Program - Revisited 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!”);
}
}
Can you answer these questions? : Can you answer these questions? What is a this reference?
What are Constructors?
What is method overloading?
What is Automatic Garbage Collection in Java?
What are the uses of the keyword static?
Inheritance (1/3) : Inheritance (1/3) 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 relevant methods
The keyword extends is used in Java to inherit a sub class from a super class public class TermInsurancePolicy extends Policy{
//Data Members and Methods
}
Inheritance (2/3) : Inheritance (2/3) The class Policy is known as the
super class
parent class
The class TermInsurancePolicy is known as
sub class
derived class
child class
Policy [Parent Class] : Policy [Parent Class] public class Policy{
private double premium;
private double maturityValue;
//Other Data
public void setPremium(double premium){
this.premium = premium;
}
public double getPremium(){return premium;}
public void setMaturityValue(double maturityValue){
this.maturityValue = maturityValue;
}
public double getMaturityValue(){return maturityValue;}
//Other Methods
}
Inheritance –child class(3/3) : Inheritance –child class(3/3) public class TermInsurancePolicy extends Policy{
private int term;
public void setTerm(int term){
this.term = term;
}
public int getTerm(){
return term;
}
public double getBenefit(){
//Calculate benefit based on
//premium, maturityValue and term
}
}
The protected Access : The protected Access The method getBenefit() needs to access the data members premium and maturityValue of the class Policy
A class member that has the protected access specifier can be accessed by the sub classes also
maturityValue and premium should be declared as protected public class Policy{
protected double premium;
protected double maturityValue;
//Other Members
}
Creating the sub class Object : Creating the sub class Object A TermInsurancePolicy object can invoke all the public methods of the class Policy and those that are newly added in TermInsurancePolicy
Thus code reusability is achieved TermInsurancePolicy policy = new TermInsurancePolicy();
policy.setPremium(100);
policy.setMaturityValue(5000);
policy.setTerm(36);
System.out.println(policy.getBenefit());
Inheritance : Inheritance Note: Inheritance is represented by a triangle head arrow in UML Class diagrams
Multi-Level Inheritance : Multi-Level Inheritance A class can be further inherited from a derived class
Multiple Inheritance : Multiple Inheritance Concept of a class inheriting from more than one base class
A Hybrid car can inherit from FuelCar and BatteryCar
Multiple inheritance is rarely used because of the complexities it brings in
Modern OO languages like Java and C# don’t support Multiple Inheritance
More on Inheritance : More on Inheritance Any number of sub classes can be created from a base class
Consider a class EndowmentPolicy
EndowmentPolicy is a Policy; EndowmentPolicy is extended from Policy
Extra data members and methods are added public class EndowmentPolicy extends Policy{
//Data Members and Methods
}
Can you answer these questions? : Can you answer these questions? What is a protected access?
What is multilevel inheritance?
Thank You : Thank You
Slide 38 :