- Java: Local methods (or submethods, or inner methods, or nested methods)
- Using a lambda (Java 8+)
- Using anonymous subclasses
- Using local classes
- Local Scoping
- Java Class Methods
- Example
- Example
- Static vs. Public
- Example
- Access Methods With an Object
- Example
- Example explained
- Remember that..
- Using Multiple Classes
- Main.java
- Second.java
- Defining Methods
- Naming a Method
- Overloading Methods
- Java Methods
- Create a Method
- Example
- Example Explained
- Call a Method
- Example
- Example
Java: Local methods (or submethods, or inner methods, or nested methods)
Java does not support local methods. This will not compile:
class C < void m() < void n() < System.out.println("Hello World"); > n(); > >
Here are a few alternatives that do compile…
Using a lambda (Java 8+)
class C < void m() < Runnable r = () -> < System.out.println("Hello World"); >; r.run(); > >
You may also access local variables, pass arguments and read return values:
import java.io.PrintStream; import java.util.function.Function; class C < void m() < PrintStream pw = System.out; FunctionString, Integer> print = str -> < pw.println(str); return str.length(); >; int charsPrinted = print.apply("Hello World"); > >
Using anonymous subclasses
Slightly more verbose than the above, but works in Java 7 and below.
class C < void m() < Runnable r = new Runnable() < public void run() < System.out.println("Hello World"); >; >; r.run(); > >
Using local classes
class C < void m() < class Local < void n() < System.out.println("Hello World"); > > new Local().n(); > >
Note that local classes comes with some restrictions:
- A local class is visible only within the block that defines it; it can never be used outside that block.
- Local classes cannot be declared public, protected, private, or static. These modifiers are for members of classes; they are not allowed with local variable declarations or local class declarations.
- Like member classes, and for the same reasons, local classes cannot contain static fields, methods, or classes. The only exception is for constants that are declared both static and final.
- Interfaces cannot be defined locally.
- A local class, like a member class, cannot have the same name as any of its enclosing classes.
- As noted earlier, a local class can use the local variables, method parameters, and even exception parameters that are in its scope, but only if those variables or parameters are declared final. This is because the lifetime of an instance of a local class can be much longer than the execution of the method in which the class is defined. For this reason, a local class must have a private internal copy of all local variables it uses (these copies are automatically generated by the compiler). The only way to ensure that the local variable and the private copy are always the same is to insist that the local variable is final. Java in a Nutshell, Chapter 3.11.2
Local Scoping
If all you’re after is localized scoping, you can simply do:
class C < void m() < < int i = 7; System.out.println(i); > // System.out.println(i); Wouldn't compile. i is out of scope. > >
Java Class Methods
You learned from the Java Methods chapter that methods are declared within a class, and that they are used to perform certain actions:
Example
Create a method named myMethod() in Main:
myMethod() prints a text (the action), when it is called. To call a method, write the method’s name followed by two parentheses () and a semicolon;
Example
Inside main , call myMethod() :
public class Main < static void myMethod() < System.out.println("Hello World!"); >public static void main(String[] args) < myMethod(); >> // Outputs "Hello World!"
public class MyClass <
static void myMethod(int x) <
System.out.println(x);
>
public static void main(String[] args) myMethod(10);
>
>
Static vs. Public
You will often see Java programs that have either static or public attributes and methods.
In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public , which can only be accessed by objects:
Example
An example to demonstrate the differences between static and public methods:
public class Main < // Static method static void myStaticMethod() < System.out.println("Static methods can be called without creating objects"); >// Public method public void myPublicMethod() < System.out.println("Public methods must be called by creating objects"); >// Main method public static void main(String[] args) < myStaticMethod(); // Call the static method // myPublicMethod(); This would compile an error Main myObj = new Main(); // Create an object of Main myObj.myPublicMethod(); // Call the public method on the object >>
Note: You will learn more about these keywords (called modifiers) in the Java Modifiers chapter.
Access Methods With an Object
Example
Create a Car object named myCar . Call the fullThrottle() and speed() methods on the myCar object, and run the program:
// Create a Main class public class Main < // Create a fullThrottle() method public void fullThrottle() < System.out.println("The car is going as fast as it can!"); >// Create a speed() method and add a parameter public void speed(int maxSpeed) < System.out.println("Max speed is: " + maxSpeed); >// Inside main, call the methods on the myCar object public static void main(String[] args) < Main myCar = new Main(); // Create a myCar object myCar.fullThrottle(); // Call the fullThrottle() method myCar.speed(200); // Call the speed() method >> // The car is going as fast as it can! // Max speed is: 200
Example explained
1) We created a custom Main class with the class keyword.
2) We created the fullThrottle() and speed() methods in the Main class.
3) The fullThrottle() method and the speed() method will print out some text, when they are called.
4) The speed() method accepts an int parameter called maxSpeed — we will use this in 8).
5) In order to use the Main class and its methods, we need to create an object of the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java method that runs your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar .
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run the program using the name of the object ( myCar ), followed by a dot ( . ), followed by the name of the method ( fullThrottle(); and speed(200); ). Notice that we add an int parameter of 200 inside the speed() method.
Remember that..
The dot ( . ) is used to access the object’s attributes and methods.
To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ).
A class must have a matching filename ( Main and Main.java).
Using Multiple Classes
Like we specified in the Classes chapter, it is a good practice to create an object of a class and access it in another class.
Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory:
Main.java
public class Main < public void fullThrottle() < System.out.println("The car is going as fast as it can!"); >public void speed(int maxSpeed) < System.out.println("Max speed is: " + maxSpeed); >>
Second.java
When both files have been compiled:
Defining Methods
The only required elements of a method declaration are the method’s return type, name, a pair of parentheses, () , and a body between braces, <> .
More generally, method declarations have six components, in order:
- Modifierssuch as public , private , and others you will learn about later.
- The return typethe data type of the value returned by the method, or void if the method does not return a value.
- The method namethe rules for field names apply to method names as well, but the convention is a little different.
- The parameter list in parenthesisa comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, () . If there are no parameters, you must use empty parentheses.
- An exception listto be discussed later.
- The method body, enclosed between bracesthe method’s code, including the declaration of local variables, goes here.
Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.
Definition: Two of the components of a method declaration comprise the method signaturethe method’s name and the parameter types.
The signature of the method declared above is:
calculateAnswer(double, int, double, double)
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:
run runFast getBackground getFinalData compareTo setX isEmpty
Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.
Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled «Interfaces and Inheritance»).
Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each methodfor example, drawString , drawInteger , drawFloat , and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw , each of which has a different parameter list.
public class DataArtist < . public void draw(String s) < . >public void draw(int i) < . >public void draw(double f) < . >public void draw(int i, double f) < . >>
Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.
You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println() , but you can also create your own methods to perform certain actions:
Example
Create a method inside Main:
Example Explained
- myMethod() is the name of the method
- static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.
- void means that this method does not have a return value. You will learn more about return values later in this chapter
Call a Method
To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main , call the myMethod() method:
public class Main < static void myMethod() < System.out.println("I just got executed!"); >public static void main(String[] args) < myMethod(); >> // Outputs "I just got executed!"
A method can also be called multiple times:
Example
public class Main < static void myMethod() < System.out.println("I just got executed!"); >public static void main(String[] args) < myMethod(); myMethod(); myMethod(); >> // I just got executed! // I just got executed! // I just got executed!
In the next chapter, Method Parameters, you will learn how to pass data (parameters) into a method.