What is method: A method is a block of code that performs a specific task and declared within the class. Methods are fundamental to object-oriented programming in Java, as they encapsulate the behavior of objects.
className object = new className;
here, className refers to data type.
Method is some kind of action. Void return type is used. This will not return any value.
Method definition should not be given inside a method.
Ex:
class Shop{
String prod_name;
int price;
public static void main(String[] args){
Shop prod1 = new Shop();
Shop prod2 = new Shop();
prod1.prod_name = "soap";
prod1.price = 50;
prod2.prod_name = "milk";
prod2.price = 150;
prod2.buy();
prod1.buy();
}
public void buy(){
System.out.println("buy method");
System.out.println(prod_name + " => " +price);}
}
Output:
buy method
milk => 150
buy method
soap => 50
Top comments (0)