Chap2 Part1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

Object Oriented

Programming
Methods Java

Parameters
Access Non access Return type
modifier modifier

public [static/final/abstract] void/[type] method1 ( String args, int i)


{
……
……
……
[return;]
}

Method Return Method


Body statement name
Methods Java

Defines the behavior of the object. Contains business logic.


Signature consists of the following :

 Access specifier : Decides the visibility and scope of the given method.
Non access specifier : Optional. Further decides the scope and use of the
method.
Method name : The name given to the method. It should to begin with
‘ small’ letter and has to follow Java Beans naming
conventions .
 Parameter(s) : Optional. If mentioned tells what type of data the method
accepts as input.
 Method body : This holds the actual method logic.
 Return statement : Optional. If the method has a specific return type then
this statement has to return the object of that particular
type . This will be the last statement in a method.

 Return type : Will be ‘void’ when the method returns nothing. Else it could be any of the
Java data type or custom types. Return type is not a part of the standard
method signature.
.
Building Blocks of Class Java

variables

Initialization code blocks

constructors

methods

CLASS
Class - Concept Java

A container of variables, objects and methods is called a CLASS.


A class can be defined as a template/ blue print that describe the behavior/states that
object of its type.

 In OOP, CLASS is of prime importance.


There can be only one public class and one or more non-public classes per source file.


Source file should be named after the PUBLIC class within it.


If the class is defined inside a package, then the package statement should be the first
statement in the source file.


Class has 4 access specifiers viz : private, default, protected and public.


It also has some non-access specifiers viz : abstract, final, static, etc.
Class – Structure Java

Step 1 . Each class begins with access modifier, keyword class and name of class
public class Employee

Step 2 . Limit/Scope/Boundary of every class is determined by pair of open- close curly


brackets. Within these brackets we include variables, constructor, methods belonging to
that class.
public class Employee
{

Step 3 Let us add some variable of Employee class. To read more about variables refer
ExtraReading Section towards the end of this ppt.

public class Employee


{
String empName;
int age;
double salary;
}
Class – Structure Java

Step 4 . Now let us add method to our class. To read more about methods, refer Extra
Reading section towards end of this ppt.

public class Employee


{
String empName;
int age;
double salary;

public double calculateEmpSal(double sal)


{
double finalSal=0.0;
finalSal = sal+10000.00;
return finalSal;
}

}
Class – Structure Java

Step 5 . Now let us add/ import packages of Java libraries and pre-defined classes into our
file. This is done by placing import statements at the beginning of our source file.

import java.io.*; Imported file(s)

public class Employee


{ Class name starting with capital letter and
access modifier and keyword class
String empName;
int age;
double salary;
Instance variables

public double calculateEmpSal(double sal)


{
double finalSal=0.0; Class method
finalSal = sal+10000.00;
return finalSal;
}
Pair of opening and closing curly brackets to fix
} scope of the class.
Class – Video Link Java

To understand more class creation watch ClassCreation video


Class – Activity 1 Java
1. Write a class Student. Identify its attributes. Write a method calculateMarks(). This
method should accept marks of Maths, English and Science and calculate their total
and return it. Fill in the missing syntax to complete above class.
public ……….. Student
{
String name;
int rollNbr;
double engMrk;
……….. sciMrk;
……….. mthMrk;

……….. ……….. void ………..(double eM, double ……….. , ……….. mtM)


{
double total=0
total = ……….. + ……….. + ……….. ;
return total;
}
………..
Class – Activity 1 Java
2. Write a class Pizza. Identify its attributes. Write a method bakePizza(). This method
should accept values for pizzaBase, topping and size. Print a message from within this
method.
3. Write a class Car. Identify its attributes. Write a method setCarDetails(). This method
should accept values for all attributes of Car and assign them to corresponding instance
variables.
Object Java

In simple terms they can be thought as the actual representation of a class.


They have ‘States’ (attributes) and ‘Behavior’ (methods).


The ‘new’ key word is used to create new objects.


There are three steps when creating an object of a class:

Declaration : Declare a variable of a given class.


Aa

Instantiation : Use new operator to allot memory to the object.


A a = new

Initialization : The 'new' keyword is followed by a call to a constructor. This call


initializes the new object.
A a = new A();
Class – Activity 2 Java
1. Write code to create object for classes created in Activity1.
Let us create object for Student class as follows :
Student stdObj = new Student();
This can be represented as below:
Student stdObj = (123999)

name

rollNbr

engMrk

sciMrk

mthMrk

calTotal()
123999
Constructor Java
 Called at the time of Object creation.


Name of constructor must be same as name of Class.


Can not have any return type. And it is NOT a method.

 Can have object initialization code within it.


Can be overloaded.


Every class (even abstract ) has a constructor.


Can be public, protected or private. Singleton pattern is popular example of Class with
private constructor.


Can not be abstract, static, final or synchronized.
Constructor Java

 Constructors can be defined in any one or all these ways


a. Non parameterized constructor
b. Parameterized constructor

If no explicit constructor is specified by programmer, Java Compiler inserts a default


Constructor.

When there are more than one constructors defined within a class it is called as
Constructor Overloading. Which form of constructor to invoke at runtime is decided by
considering the number and data type of arguments passed. If there are no arguments
passed then non-parameterized constructor is called.
Object and Constructor relation Java
For above class consider the following code:

Employee empObj1 = new Employee();


Employee empObj2 = new Employee(“ABC”,24,10500);

Above lines will call following constructors:

public Employee(String eNm, int ag, double sal)


{
empName=eNm;
age=ag;
salary=sal;
}
public Employee()
{
}
Constructor – Non Parameterized Java
Let us modify Employee class to have a constructor.

public class Employee


{
String empName;
int age; Constructor having same name as
double salary; class and public access modifier. It
does not take any parameters so it is
public Employee() a NON – PARAMETERIZED
{ constructor. It is used to initialize
empName=null; instance variables.
age=0;
salary=0.0;
}
public double calculateEmpSal(double sal)
{
double finalSal=0.0;
finalSal = sal+10000.00;
return finalSal;
}
}
Constructor - Parameterized Java
Let us modify Employee class to have a constructor.

public class Employee


{
String empName;
int age;
double salary;
This is a
PARAMETERIZED
public Employee(String eNm, int ag, double sal)
constructor which
{ accepts arguments
empName=eNm; viz, eNm, ag and sal.
age=ag; These arguments are
salary=sal; corresponding to
} instance variables
public double calculateEmpSal(double sal) and are assigned to
{ them within
constructor.
double finalSal=0.0;
finalSal = sal+10000.00;
return finalSal;
}
}
Constructor – Over Loaded Java
Let us modify Employee class to have a constructor.

public class Employee


{
String empName;
int age;
double salary;
We have 2
constructors here.
public Employee(String eNm, int ag, double sal)
One which accepts
{ parameters and other
empName=eNm; which does not.
age=ag; When there are more
salary=sal; than ONE
} constructors within a
public Employee() class it is said to have
{ OVER LOADED
constructors.
}
}
Class – Activity 3 Java
1. Modify class Student and add a Non-Parameterized constructor to it. Add a print
statement to the constructor to understand the flow of execution.
2. Add a parameterized constructor to Class Pizza. Constructor should accept values for
pizzaBase, topping and size and assign those to instance variables.
3. Modify class Car to have one non-parameterized constructor and one parameterized
constructor. Understand flow of execution and constructor calls while object creation.
To do so, complete the following code..
class Cars{
instance variables go here
public Cars(){
}
public Cars(arguments){
}
public static void main(String args[]){
Cars carObj1 = new Cars();
Cars carObj2 = new Cars(args);
}
}
Class – Video Link Java

To understand more on object creation and constructors,


watch ObjectsAndConstructors video
Class – Video Link Java

To understand more on access modifiers in Java watch,


AccessModifiersPart1,2 and 3 videos
Access modifiers Java


In order to control outside access to information various levels of access or visibility are
designed in Java. These are called as Access Modifiers.


Access modifiers decide who will get to see/use the given property, method or class.


There are 4 types of access modifiers applicable across class, sub-class and packages.


The 4 access modifiers are : public, default, protected and private.
Access modifiers Java

different
same same pkg
pkg pkg different different
Access same differen subcla pkg class
Modifier class t class ss Subclass
Y Y Y N N Package level
default

private Y N N N N Class level

protected Y Y Y Y N Subclass level


Y Y Y Y Y
public All levels
Class – Activity 4 Java

1. Referring to AccessModifiers videos, add following 4 variables to your Vehicle class and
try accessing those from different other class created to test access modifiers.

private String vehicleManufacturer;


protected String vehicleNumber;
double vehiclePrice;
public String vehicleModel;
Garbage Collection Java
 Garbage collection is a way JVM cleans up space on the heap for memory management.

Carried out by daemon thread called Garbage Collector when JVM needs to create new
objects or run threads and programs.

 Any object that is no longer active or no longer has any references is eligible for
garbage collection.


Some cases in which an object gets marked for GC are as follows:

• All references of that object explicitly set to null e.g. object = null

• Object is created inside a block and execution of that block is over.

• The parent object which holds this object is set to null

• Object has only live references via WeakHashMap


Though programmer need not worry about GC and memory management the code
can request for GC by using methods like System.gc() or Runtime.gc() . But there is no
guarantee that GC will be invoked by the JVM.
Garbage Collection – finalize() Java
finalize() :

 Called before the object is collected by the GC.


Syntax is
protected void finalize()throws Throwable
{
//tasks to be done before object is garbage collected.
}

Releasing system resources such as open files, open sockets, network connections should
be done within finalize().


By calling System.runFinalization() OR Runtime.getRuntime().runFinalization() ensures
that JVM call finalize() method of all object which are eligible for garbage collection and
whose finalize has not yet called.
Initialization Code Blocks Java
 Initializer block contains the code that is always executed whenever an instance is
created. They are also called as Instance Initialization Blocks (IIB).
 IIBs are executed before constructors and run each time at object creation.
 Including IIB in your class is optional but if included they are placed before constructor.
 Consider,
public class Employee{
{
System.out.println(“Hello from IIB of Employee class”);
}
public Employee(){
IIB within Employee
class. It has NO NAME, System.out.println(“Hello from constructor of Employee class”);
NO SIGNATURE. It
}
begins and ends with
curly brackets { }. public static void main(String args[]){
Employee empObj = new Employee();
}
}
Argument passing – call by value Java
 How arguments are passed to a called function is called as argument passing. This is
done is various ways like call by value, call by reference, etc.

 Java supports ONLY call by value.

 Arguments which are passed could be primitive data types, arrays or objects. All these
are always passed by using call by value.

 Java DOES NOT allow call by reference.

 When primitive values are passed as arugments they behave differently as compared to
when Objects are passed as arguments.
Argument passing – call by value – primitive type Java
We need to double the salary of given employee. For this we write a separate class, Salary
and in that class we write a method, updateSalary().

To this method we pass employee’s existing salary and double it.

public void updateSalary(double oldSalary)


{
oldSalary=oldSalary*2;
}

We will call this method from main() in Salary class as shown ahead.
Argument passing – call by value – primitive type Java
public static void main(String args[])

Employee emp1 = new Employee("Pqr",30,15000,emAdr); emp1.empSal


System.out.println("Employee salary before updating..."+emp1.empSal); 15000

salaryObj.updateSalary(emp1.empSal);
15000

oldSalary
public void updateSalary(double oldSalary) 15000
{
oldSalary=oldSalary*2; oldSalary
} 30000

emp1.empSal
System.out.println("Update salary of employee is..."+emp1.empSal); 15000
Changes done inside method NOT seen outside when PRIMITIVE values are passed as
method arguments.
Argument passing – call by value - Object Java
For PERMANENT changes we need to pass the object of Employee class as method argument.
This is done by modifying the above method within Salary class

public void updateSalary(Employee tempEmp)


{
tempEmp.sal = tempEmp.sal*2;
}
Argument passing – call by value - Object Java
stack empObj
Heap
name = null
Employee empObj = new Employee(); empObj=(3440) sal = 0.0

3440
empObj.name=“PQR”; empObj
empObj.sal = 15000; name = “PQR”
sal = 15000

dptObj.updateSalary(empObj);
3440
(3440)

empObj=(3440) 3440
updateSalary(Employee tempEmp)
tempEmp =(6546)

6546
Heap after changes in values
empObj
name = “PQR”
tempEmp.sal = tempEmp.sal*2 sal =30000
3440
Argument passing – call by value Java

To understand more about passing arguments to a function


watch callbyvalue
Method Overloading Java

 Method overloading means having two or more methods with the same name but
different signatures.


Method overloading is resolved using static binding at compile time.


Overloaded methods can remain in the same class.


Constructors can also be overloaded.

 One should consider overloading a method when you have same methods that take
different signatures, but conceptually do the same thing.
Method Overloading Java
Consider the following code :

class MethodOverloading System.out.println("I have "+angles+"


{ angles"); }
//the following method takes a String argument. }
public void describe(String shape)
{
System.out.println("I am a "+shape);
}
//the following overloaded method takes an int
argument.
public void describe(int angles)
{
public class MethodOverloadingDemo {
public static void main(String args[])
{
MethodOverloading descShape =new
MethodOverloading();
descShape.describe(3);
descShape.describe("triangle"); }

}
Method Overloading Java

In the above eg we have two methods having the same name as, describe. But the signatures
of these 2 methods are different. One method takes a String while the other one takes an int.
This is method overloading.

While deciding which method to invoke, the JVM first looks at the type of the argument
which is passed while calling the method. Depending on this argument (and the number of
arguments) the compiler selects that version of the given method.

Thus while calling describe() when the call is passing a String argument the string version of
the method is called and when the call is passing an int, the int version of the method is
called.

Thus the output is :

I have 3angles
I am a triangle
Class – Activity 5 Java
1. Write a public class Draw. This class should have following things:
a. instance variables : shapeName, shapeSides
b. parameterized constructor which accepts arguments for shape name and
shape sides and assigns them to corresponding instance variables.
c. method, drawShape() which takes the name of the shape. Print the name from
within the method.
d. overloaded method, drawShape() which takes the number of sides and prints
it from within the method.
e. overloaded method, drawShape() which takes the name and number of sides
and prints it from within the method.
f. main() which will create object of Draw class and invoke all overloaded
methods.

Check the code snippet in next slide and complete it.


Class – Activity 5 – Solution snippet Java
??? java.io.*; //overloaded drawShape()
??? class Draw ??? void drawShape(??? ???)
{ {
//instance variables System.out.println("Name of the shape is: "+???);
??? shapeName; }
int ???; //overloaded drawShape() with 2 parameters.
//parameterised constructor public void ???(??? ??? , ??? ???)
??? ???(??? shpNm,??? sds) {
{ System.out.println("Name of the shape is: "+???);
shapeName=shpNm; ???.out.println(???);
??? = ???; ???
???
//drawShape method with int parameter.
public void drawShape(int nbrSds)
{
System.out.println("No of sides are: "+nbrSds);
}
Class – Activity 5 – Solution snippet Java

//main method
public static void main(String args[])
{
Draw objDrw = ??? Draw(??? , ???);
objDrw.drawShape(3);
objDrw.???;
???.drawShape(???,???);
}

}
Recursion Java
Self study

Refer:
https://www.baeldung.com/java-recursion
https://www.programiz.com/java-programming/recursion

Please see :
Rest of the chapter will be continued in Part2 notes .
What we learnt? Java

You might also like