Professional Documents
Culture Documents
Chap2 Part1
Chap2 Part1
Chap2 Part1
Programming
Methods Java
Parameters
Access Non access Return type
modifier modifier
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
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.
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 3 Let us add some variable of Employee class. To read more about variables refer
ExtraReading Section towards the end of this ppt.
Step 4 . Now let us add method to our class. To read more about methods, refer Extra
Reading section towards end of this ppt.
}
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.
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:
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 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
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:
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
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.
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
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.
Arguments which are passed could be primitive data types, arrays or objects. All these
are always passed by using call by value.
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().
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[])
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
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
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 :
}
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.
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.
//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