The document discusses different types of methods in Java. It defines a method as a block of code that performs a specific task. It then explains how to declare a method using access specifiers, return types, and parameters. It also provides guidelines for naming methods and describes different types of methods including predefined, user defined, static, instance, abstract, and factory methods. Key details about each type of method are given such as how they are invoked and implemented.
4. INTRODUCTION
• The method in Java is a collection of instructions that
performs a specific task.
• A method is a block of code or collection of
statements or a set of code grouped together to
perform a certain task or operation.
• It is used to achieve the reusability of code.
• It also provides the easy
modification and readability of code, just by adding
or removing a chunk of code.
• The method is executed only when we call or invoke
it.
5. Method Declaration
public int sum(int a, int b)
{
//method body
}
public Access specifier
int return type
sum method name
(int a,int b) parameters
6. Naming a Method
• Use a name that corresponds to the functionality (if
the method is adding two numbers, use add() or
sum())
• The method name should start with a verb and in
lowercase (Ex: sum(), divide(), area())
• For a multi-word name, the first word should be a
verb followed by a noun or adjective without any
space and with the first letter capitalized
(Ex: addIntegers(), areaOfSquare)
8. User defined Methods
• Static Method
• Instance Method
• Abstract Method
• Factory method
9. Static Method
• A method that has static keyword is known as
static method.
• The main advantage of a static method is that we
can call it without creating an object.
• It is invoked by using the class name.
• The best example of a static method is
the main() method.
10. Instance Method
• The method of the class is known as
an instance method.
• It is a non-static method defined in the class.
•
• Before calling or invoking the instance
method, it is necessary to create an object of its
class.
11. Abstract Methods
• Abstract methods in Java do not have any code in
them. This means that there is no need to provide
the implementation code while declaring it.
• Instead, it is possible to declare the method body
later in the program.
• It is known that one can declare an abstract
method by using the “abstract” keyword.
• There is another hard rule to declare abstract
methods, and it is that they can only be declared
within an abstract class.
12. Factory Method
• Factory methods are the ones that return an
object to the class where it belongs.
• Usually, all static methods also fall into this
type of method.