Object Oriented Programming

Standard Methods in Java

A method is a block of code that can be called from another location in the program or class. It is used to reduce the repetition of multiple lines of code. The return statement concludes the execution of the block of code, returning something of type provided in the method header, or null (void method).

modifier dataType methodName (methodParameters) {  //method header
    //statements that execute when called

//method call within the class:

//method call outside of the class, access using an object instance


methodName is defined by the programmer, dataType is the data type of the result from calling the method, and modifier is the access modifier. 'Public' allows calling of the method using the object, while 'private' methods can only be called with other methods within the class.

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.

The method can only access global methods and variables, ones passed into the method, as well as ones within the same class.

Within classes, these methods are known as 'Instance Methods', because they are accessed through an object instance of the class.

public class Numbers {
    int max = findMaximum(3,5) //call within the class, will return 5
    public Numbers() {}
    public int findMaximum(int number1, int number2) { 
        //3 stored in number1, 5 stored in number2
        int maximum = number2; 
        if (number1 > number2) maximum = number1; 
        return maximum; 

//outside the class, somewhere
Numbers numberClass = new Numbers();
int maximum = numberClass.findMaximum(3, 5);

See Also

Access Modifiers


Java Tutorials - Defining Methods

Add to Slack

< Class Variables   |   Class Methods >

© 2019 SyntaxDB. All Rights Reserved.