Static and instance method in java


Static methods are declared using static modifier.
Static method can’t access instance method and instance variables directly.
In static method we should not use ‘this’ keyword.
Static method does not need an instance to be created .It can directly be called as ClassName.Methodname(parameter)

To use the instance method we need to create specific instance of the class.


public class Main {

public static void main(String[] args) {
Animal.sheep(“Stephen”); //ClassName.Methodname(parameter)

Animal a=new Animal();
a.soundOfSheep();
}

}

class Animal {

//static method
public static void sheep(String name) {
System.out.println(“Hi, My name is “+name+” and I am a sheep!”);
}

//instance method
public void soundOfSheep() {
System.out.println(“Stephen sounds like baa baa baa baa baa…”);
}
}