Method and Modifiers in Java

Java is a high-level, class-based, programing language designed to have as few implementation dependencies as possible due to its object-oriented programming concepts and features.

Object-oriented programming(OOP) is a programming paradigm built around the concept of objects and how they interact with each other to perform the program functions. Each object can be characterized by a state and behavior, an object's state is represented by its data(fields), and operations on the data (method) represents the behavior of the object i.e what function it does and how it interacts with other objects, now this brings us back to the topic of discussion -

What is a Method?

thinking-kid.png

A method is a sequence of statements that performs a specific task and can be invoked or referred to by its name. There are two types of methods in Java, the Built-in method and the user-defined method.

Built-in methods also known as predefined or standard library methods are common functions that have been defined in the Java standard library and can be called to use at any point anywhere in your program, Some pre-defined methods are length(), equals(), random() , etc. When we call these methods to use in our program a series of codes relating to the method that has been stored in the Java standard library runs in the background. It is imperative to note that each built-in method is defined in a class, for example, the max() method that returns the maximum of two numerical values is defined in the Java.lang.Math class.

Let's see this in code

public class Example   
{  
public static void main(String[] args)   
{  
// Using the max() method of Math class  
System.out.print("The maximum number is: " + Math.max(4,6));  
    }  
}

Output

6

In contrast User-defined method is created by the programmer. It is a common practice to create a customized sub-program for a specific purpose. Let's create a user-defined method that checks whether a business is making profits or running at a loss

public class BusinessCalculator {

    public static void calculateProfit(int income, int expenditure){
        if (income - expenditure > 0){
           int profit = income - expenditure;
            System.out.println("Profit:" + profit );
        }
        else {
            int loss = income - expenditure;
            System.out.println("Loss:" + loss);
        }
    }
}

Once we have defined a method, it should be called. The calling of a method in a program is simple. When we call or invoke a user-defined method, the program control transfer to the called method.

You can call a method like this

public class Main {

    public static void main(String[] args) {

        int income = 50000;
       int expenditure = 11400;

        // Calling a method
       BusinessCalculator.calculateProfit(income, expenditure);
    }
}

Output

Profit:38600

In the above code snippet, as soon as the compiler reaches line BusinessCalculator.calculateProfit(income, expenditure) , the control transfer to the method and gives the output accordingly.

The Syntax of a Method

A method contains a set of modifiers, a type of the return value, a name, a list of parameters in parenthesis (), and a body in curly braces {}. The combination of a method name and the list of its parameters is known as the Method Signature, when you invoke a method from another class to make use of its functions, it is the name and the parameters that will be used to access the method without revealing its implementation details. example login(username, password)

If you're a beginner in Java all these terms may sound unfamiliar and confusing, but not to worry I got you covered. Let's take a look at this diagram below and analyze the components that make up a method.

method-syntax.png

The first keywords public and static are called Modifiers, there are two types of modifiers in Java: Access modifiers and Non-access modifiers.

  1. Access Modifiers In Java, access modifiers define the visibility of methods, classes, interfaces, variables, methods, constructors, data members, and the setter methods... There are four access modifiers in Java, namely -
  • public - The method will be accessible to all classes in our program.

  • private - The method is accessible only in the class in which it is defined.

  • protected - The method is accessible within the same package or sub-classes in a different package

  • default - When we do not use any access modifiers in the method declaration, it is specified as default by Java and it is visible only to classes belonging to the same package.

2. Non-access Modifiers provide information about the behavior of the method to Java Virtual Machine (JVM). The modifier static means the method belongs to the class and it can be accessed without creating an object (object is an instance of a class). If you look at the above example, calculateProfit(int income, int expenditure) method was called directly using the class name without creating an object, this type of method is called a static method, if the method is declared without the static modifier, it means the method can be invoked only by creating an object or instance of BusinessCalculator class, such methods are called instance method. See the below example

public class Main {

    public static void main(String[] args) {

        // Creating an object
        BusinessCalculator businessCalculator = new BusinessCalculator();

        int income = 50000;
       int expenditure = 11400;

        // Method called using the created object
       businessCalculator.calculateProfit(income, expenditure);

There are two types of the Instance method, accessor method and mutator method.

  • Accessor Method: This method reads instance variables, it can easily be identified because it is prefixed with the word get , also known as getters , it is used to get the value of a private field.
public int getName()    
{    
return name;    
}
  • Mutator Method: This method reads the instance variables and also modifies the values, it is prefixed with the word set also known as setters , it does not return anything, it accepts the parameter of the same data type that depends on the field, it is used to set the value of a field. e.g
public void setBaseSalary(int baseSalary){
        if (baseSalary <= 0)
            throw new IllegalArgumentException("Error");
        this.baseSalary = baseSalary;
    }

With the setter method we were able to specify a condition for the field to meet before the method can complete its execution otherwise it throws an exception. Exceptions are errors in Java.

Return type: From the above diagram the return type is an integer value, this means that before a method completes its execution and exit it returns a value known as the return value in this case it returns an integer it can also be any of the other primitive types like float, double, boolean or a reference type like String. Methods do not necessarily have to return a value if we want a method not to return a value but to perform operations only, the keyword void is used as a return type.

Method Name: This is a unique name with which the method is called. It should start with a verb followed by an adjective or noun if there is more than one word, and written in camel casing e.g save(), saveFile(), saveToFile(). A verb is an action word, and so the name of the method should directly reflect the function it performs.

Method Parameters: In parenthesis after the method name, we define the type, number, and order of the parameters. Parameters refer to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked, there are also methods that don't have values passed to them, these methods are known as non-parameterized method..

Method Body: The body holds the logic we want to implement by our method, it is a set of statements to perform with the passed values to obtain the result.

Method Overloading: It is possible for more than one method to use the same name but with a different implementation, it can be in parameter type or number. let's take an instance using the calculateProfit(int income, int expenditure), a business owner pays taxes quarterly and needs a separate method to calculate profit whenever he pays tax, such method can be declared like this

 calculateProfit(int income, int expenditure, int tax)

and whenever the method is called both implementation is shown to the programer to pick from.

Abstract Method: This method does not contain any implementation, it is usually declared in an abstract class. we use abstract classes in situations where we declare a class but don't want to be able to instantiate it or create a new instance of the class, we can only extend it. When an abstract class is subclassed, the subclass usually provides the implementation for all the abstract methods.

Factory method: It is a method that returns an object to the class to which it belongs. All static methods are factory methods. For example, NumberFormat obj = NumberFormat.getNumberInstance();

I believe you have a better understanding of method and modifiers and how you can use them in your program, if you have any questions or contributions leave a comment and I will respond.