3. Contents
1. Java Method Introduction
2. Types of Methods
1. Standard Library Methods
2. User-defined Methods
3. How to create a user-defined methods
4. Recursive Methods
5. Method Overloading
6. Method Overriding
7. Method Overloading Vs Overriding
8. Constructors
3
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
4. 1.Introduction
In mathematics, you might have studied about functions.
For example, f(x) = x2 is a function that returns squared
value of x.
If x = 2, then f(2) = 4
If x = 3, f(3) = 9 and so on.
Similarly, in programming, a function is a block of code
that performs a specific task.
In Java, method is a jargon used for function.
Methods are bound to a class and they define the behavior
of a class.
4
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
5. 2.Type of Java Methods
Depending on whether a method is defined by the user, or
available in standard library, there are two types of
methods:
1. Standard Library Methods
2. User-defined Methods
What are the advantages of using methods?
The main advantage is code reusability.
You can write a method once, and use it multiple times.
You do not have to rewrite the entire code each time. Think of it
as, "write once, reuse multiple times."
5
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
6. 2.1 Standard Library Methods
The standard library methods are built-in methods in Java
that are readily available for use.
These standard libraries come along with the Java Class
Library (JCL) in a Java archive (*.jar) file with JVM( Java
Virtual Machine and JRE (Java Runtime Environment).
For example, print() is a method of java.io.PrintSteam.
The print("...") prints the string inside quotation marks.
sqrt() is a method of Math class.
It returns square root of a number.
6
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
10. 2.2 User-defined Methods
You can also define methods inside a class as per your
wish. Such methods are called user-defined methods.
How to create a user-defined method?
Before you can use (call a method), you need to define
it. Here is how you define methods in Java.
Here, a method named myMethod() is defined.
public static void myMethod() {
System.out.println(“My Function called”);
}
10
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
12. 3. How to create a user-defined method?
Syntax for a method:
The syntax shown above includes:
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of
the method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
method body − The method body defines what the method does with the
statements.
modifier returnValueType methodName(list of parameters){
// Method body;
}
12
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
13. public static int max(int num1, int num2){
int result;
if if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Example-Define a method
int z = max(x, y);
Invoke a method
modifier
return value
type
method name
formal parameters
parameter list
return value
method
body
actual parameters
(arguments)
A parameter is a special kind of
variable in computer
programming language that is
used to pass information
between functions or procedures.
The actual information passed is
called an argument.
13
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
14. 3.1 Method Calling
For using a method, it should be called. There are two ways in
which a method is called:
1. method returns a value
2. returning nothing (no return value).
The process of method calling is simple. When a program
invokes a method, the program control gets transferred to the
called method. This called method then returns control to the
caller in two conditions, when
1. the return statement is executed.
2. it reaches the method ending closing brace.
For example
The method returning value can be understood by the following example:
int result = sum(6, 9);
System.out.println("This is return nothing!")
14
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
16. 3.2. The void Keyword (method not return Value)
The void keyword allows us to create methods
which do not return a value.
This method is a void method, which does not
return any value.
Call to a void method must be a statement
i.e. methodRankPoints(499.50);. It is a Java
statement which ends with a semicolon as shown in
the following example.
16
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
18. 3.3 Passing data in Java (Passing Values to Method)
When it comes to Java programming, one of the trickiest questions is:
Does Java pass variables to methods by reference or by value?
This has been raising a lot of debates and making confusion for beginners.
However, the ultimate answer is crystal clear:
Java always passes variables by value.
Or in other words:
Java passes object references to methods by value.
Pass-by-value: A copy of the passed-in variable is copied into the argument of
the method. Any changes to the argument do not affect the original one.
Pass-by-reference: The argument is an alias of the passed-in variable. Any
changes to the argument will affect the original one.
Note: There is only call by value in java, not call by reference
18
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
19. Example-1: Java passes object references to methods by value:
19
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
20. 3.4 Java Methods with Arguments and Return Value
A Java method can have zero or more parameters. And, they may
return a value.
20
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
21. 3.5 Method Accepting Arguments and Returning Value
21
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
22. 3.6 passing more than one argument to method by using
commas
22
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
23. Example: Get Squared Value Of Numbers from 1 to 5
23
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
24. 4.Recursive Method
A method that calls itself is known as a recursive
method.
And, this technique is known as recursion.
A physical world example would be to place two
parallel mirrors facing each other.
Any object in between them would be reflected
recursively.
24
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
25. 4.1 How recursion works?
recurse() method is called from inside the main method at first
(normal method call).
Also, recurse() method is called from inside the same method,
recurse(). This is a recursive call.
25
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
27. 4.2 Advantages and Disadvantages of Recursion
When a recursive call is made, new storage
location for variables are allocated on the stack.
As, each recursive call returns, the old variables
and parameters are removed from the stack.
Hence, recursion generally use more memory and
are generally slow.
On the other hand, recursive solution is much
simpler and takes less time to write, debug and
maintain.
27
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
28. 5. Method Overloading
Method Overloading is a feature that allows a class
to have more than one method having the same
name, if their argument lists are different.
It is similar to constructor overloading in Java, that
allows a class to have more than one constructor
having different argument lists.
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
28
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
29. 5.1 Ways to create Method Overloading
In Java, two or more methods can have same name if they
differ in parameters:
1. different number of parameters
2. different types of parameters, or both.
29
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
31. Example-2 By changing the datatype of parameters
31
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
32. 5.2 Why method overloading?
Suppose, you have to perform addition of the given numbers but
there can be any number of arguments (let’s say either 2 or 3
arguments for simplicity).
In order to accomplish the task, you can create two methods
sum2num(int, int) and sum3num(int, int, int) for two and three
parameters respectively.
However, other programmers as well as you in future may get
confused as the behavior of both methods is same but they differ by
name.
The better way to accomplish this task is by overloading methods.
And, depending upon the argument passed, one of the overloaded
methods is called. This helps to increase readability of the program
32
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
35. 6. Method Overriding
If subclass (child class) has the same method as
declared in the parent class, it is known as method
overriding in java.
In other words, If subclass provides the specific
implementation of the method that has been
provided by one of its parent class, it is known as
method overriding.
35
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
36. 6.1 Usage of Method Overriding
Method overriding is used to provide specific
implementation of a method that is already
provided by its super class.
Method overriding is used for runtime
polymorphism
36
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
37. 6.2 Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent
class.
3. must be IS-A relationship (inheritance).
37
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
38. Example of Java Method Overriding
Consider a scenario, Bank is a class that provides functionality to get
rate of interest. But, rate of interest varies according to banks. For
example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9%
rate of interest.
38
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
41. 8. Constructors in Java
Constructor is a block of code that initializes the newly
created object.
A constructor resembles an instance method in java but it’s
not a method as it doesn’t have a return type.
Constructor has same name as the class and looks like this
in a java code.
Note that the constructor name matches with the class
name and it doesn’t have a return type.
41
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
42. 8.1 How does a constructor work
Here we have created an object obj of class Hello and then we
displayed the instance variable name of the object.
The output ‘‘BeginnersBook.com’’passed to the name during
initialization in constructor.
This shows that when we created the object obj the constructor got
invoked. this keyword refers to the current object, object obj in this
example.
42
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
43. 8.1 How does a constructor work
To understand the working of constructor, lets take an example.
lets say we have a class MyClass. When we create the object of
MyClass like this: MyClass obj = new MyClass()
The new keyword here creates the object of class MyClass and
invokes the constructor to initialize this newly created object.
43
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
44. 8.2 Types of Constructor works
There are three types of constructors:
Default,
No-arg constructor
Parameterized.
44
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
45. 8.2.1 Default constructor
If you do not implement any constructor in your
class, Java compiler inserts a default constructor
into your code on your behalf.
This constructor is known as default constructor.
You would not find it in your source code(the java
file) as it would be inserted into the code during
compilation and exists in .class file.
This process is shown in the diagram below:
45
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
46. 8.2.1 Default constructor ( Cont’d)
If you implement any constructor then you no longer
receive a default constructor from Java compiler.
46
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
47. 8.2.2 no-argument constructor
Constructor with no arguments is known as no-arg
constructor.
The signature is same as default constructor, however body
can have any code unlike default constructor where the
body of the constructor is empty.
Although you may see some people claim that that default
and no-arg constructor is same but in fact they are not,
even if you write public Demo() { } in your class Demo it
cannot be called default constructor since you have written
the code of it.
47
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
49. 8.2.3 Parameterized constructor
Constructor with arguments(or you can say
parameters) is known as Parameterized constructor.
Example: parameterized constructor
In this example we have a parameterized
constructor with two parameters id and name.
While creating the objects obj1 and obj2 I have
passed two arguments so that this constructor gets
invoked after creation of obj1 and obj2.
49
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
51. Example2- Parameterized constructor
In this example, we have two
constructors, a default
constructor and a parameterized
constructor.
When we do not pass any
parameter while creating the
object using new keyword then
default constructor is invoked,
however
when you pass a parameter then
parameterized constructor that
matches with the passed
parameters list gets invoked.
51
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
52. 8.3 Constructor Chaining
When A constructor calls another constructor of same class then this is
called constructor chaining.
52
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
53. 8.3.1 Constructor Chaining: super()
Whenever a child class constructor gets invoked it implicitly invokes
the constructor of parent class. You can also say that the compiler inserts
a super(); statement at the beginning of child class constructor.
53
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍
54. 8.4 Constructor Overloading
Constructor overloading is a concept of having more than one
constructor with different parameters list, in such a way so that each
constructor performs a different task.
54
@LimLyheng
ែចកចំេណះនិងបទពិេសធន៍