Object Oriented Programming

Class Methods in Java

Class methods are methods that are called on the class itself, not on a specific object instance. The static modifier ensures implementation is the same across all class instances. Many standard built-in classes in Java (for example, Math) come with static methods (for example, Math.abs(int value)) that are used in many Java programs.


Syntax
public class className {
    modifier static dataType methodName (inputParameters) { //static method
         //block of code to be executed
    }
}

//calling the method, from anywhere
className.methodName(passedParams);

Notes

methodName is defined by the programmer, dataType is the data type of the result from calling the method, and modifier is the access modifier. The 'static' keyword is an additional modifier that makes the method static.

methodParameters contain data used within the method, stored using variables. Parameters are defined as: (dataType parameterName), which is the data type of the input parameter and the name of the parameter as seen within the method. There can be multiple parameters separated by a comma.

Static methods are called without instantiation. This means that static methods can only access other static members of the class (and of course, global and passed in variables), because other members are object members. They, however, can be called on an object, but this is discouraged.


Example
public class Numbers {
    public Numbers() {}
    public static int findMinimum(int number1, int number2) { 
        //3 stored in number1, 5 stored in number2
        int minimum = number2; 
        if (number1 < number2) minimum = number1; 
        return minimum; 
    }
}

//calling method outside of the class
int min = Numbers.findMinimum(3, 5);
//this would NOT work, static methods cannot be accessed with an object
min = numberClass.findMinimum(3, 5);

See Also
Documentation

Static Class Members

Add to Slack

< Standard Methods   |   Inheritance >

© 2018 SyntaxDB. All Rights Reserved.