Method in Java
Method is set of code or instruction to perform some operation.
It is used to represent the behaviour of an object.
A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().
For Example :
class Hello{
void show(){
//write code here...
}
}
Rules for a method :
Method must have an access modifiers like private, default, protected or public.
Method has an optional to use non access modifiers like static, final, abstract, synchronized etc.
Method must have a return type.
Method must have a name or identifiers in which we call a method.
Method name should be declare in camel case like add(), addTwoNumber() etc.
There are two type of methods in Java :
1. Non-Parameterized Method
2. Parameterized Method
//non-parameterized
void show(){
}
//parameterized
void add(int i,int j){
}
We can make a Parameterized Method when you get input from user and when you dont get input from user we use Non-Parameterized Method.
We can define a method in two way :
1. Static Method
2. Non-Static Method
//static method
static void show(){
}
//non-static method
void add(int i,int j){
}
When you want to share a method from different object of the same class we use static method and when you dont want to share a method from different object of same class we use non-static method.
Method can be return any type of data like Primitive data or Non-Primitive data.
//It return the Primitive type of Data.
public int add(int i,int j){
return i+j;
}
//It return Dog type of object and here Dog is Non-Primitive Data.
public Dog getDog(){
return new Dog();
}
//It can never return a value because its return type is void.
void display(){
}
Various valid type of method declaration :
//definition of a method
public void show(){
}
//definition of a method
private void show(){
}
//definition of a method
void show(){
}
//definition of a method
protected void show(){
}
//definition of a method
public final void show(){
}
//declaration of a method
public abstract void show();
//definition of a method
final public void show(){
}
//definition of a method
public final static void show(){
}
2 comments:
Thank you sir For This Blog,It's really Helpful.
I Really Appriciate your Work .
guru ji apke blog was awesome
Post a Comment