Method in Java
Method in Java
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.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type, name,
and arguments.
Method Declaration
Predefined methods are the method that is already defined in the Java class libraries is known as predefined
methods.
It is also known as the standard library method or built-in method.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class.
User-defined Method
A method that has static keyword is known as static method. In other words, a method that belongs to a class
rather than an instance of a class is known as a 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.
Instance Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. It is
also known as getters.
Example:
public int getId()
{
return Id;
}
Mutator Method
Mutator Method: The method(s) read the instance variable(s) and also modify the values. It is also known
as setters or modifiers.
Example:
public void setRoll(int roll)
{
this.roll = roll;
}
Abstract Method
The method that does not has method body is known as abstract method. In other words, without an
implementation is known as abstract method. It always declares in the abstract class. It means the class
itself must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract.
Syntax:
abstract void method_name();
Example:
abstract class Demo //abstract class
{
//abstract method declaration
abstract void display();
}
Encapsulation in Java
Encapsulation in Java
By providing only a setter or getter method, you can make the class read-only or write-only. In other
words, you can skip the getter or setter methods.
It provides you the control over the data.
It is a way to achieve data hiding in Java.
The encapsulate class is easy to test.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to
create an encapsulated class in Java.
THANK
YOU