In Java, the method is a collection of statements that performs a specific task or operation. It is widely used because it provides reusability of code means that write once and use it many times. It also provides easy modification. Each method has its own name by which it is called. When the compiler reads the method name, the method is called and performs the specified task. In this section, we will learn how to call pre-defined, user-defined, static, and abstract methods in Java.
Example program:
class SuperMarket // Class name
{
String name;
int price;
static String shop_name ="Saravana";
public static void main(String[] args)
{
System.out.println("Welcome");
SuperMarket prod1 = new SuperMarket();// new keyword
prod1.name="Bread";
prod1.price=20;
SuperMarket prod2 = new SuperMarket();
prod2.name="Biscuit";
prod2.price=15;
SuperMarket prod3 = new SuperMarket();
prod3.name="Candy";
prod3.price=12;
prod3.buy(); // Method Calling
}
void buy() // Method definition
{
System.out.println("Buying Things");
System.out.println(name);
System.out.println(price);
System.out.println(SuperMarket.shop_name);
}
}
Output:
command
Welcome
Buying Things
Candy
12
Saravana