- Defining Methods
- Naming a Method
- Overloading Methods
- 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
- Class Methods in Java | Explained
- Class Method in Java
- How to Access Class Methods
- How to Access Public Methods
- How to Access a Method from a Different Class
- MyFunctions.java
- AddNumbers.java
- AddNumbers.java
- Conclusion
- About the author
- Anees Asghar
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 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:
Class Methods in Java | Explained
In Java, a method is nothing but a block of code/statement that is declared within the class and can perform different actions when someone calls it. Some methods can be called directly with their name (i.e. without creating the class object) while some methods require instance/object of the class (i.e. must be invoked with the object of the class).
The methods that can be called directly are referred as a class or static methods, while the methods that need an object of the class to be invoked are referred as instance or non-static methods.
This write-up will present a detailed overview of class methods and in this regard, it will cover the following aspects of Java class methods:
Class Method in Java
Generally, when we have a class then we have to create an object of that class to access its methods and other members. However, the class/static methods can be accessed inside of the class without creating an instance of that class.
How to Access Class Methods
Let’s consider the below-given example to understand how to create and access a static/class method in Java.
The below code snippet takes two numbers from the user and perform addition on them:
public static int addition ( int num1, int num2 ) {
int add = num1 + num2 ;
return add ;
}
public static void main ( String [ ] args ) {
int number1, number2, sum ;
Scanner scan = new Scanner ( System . in ) ;
System . out . print ( «Enter 1st number: » ) ;
number1 = scan. nextInt ( ) ;
System . out . print ( «Enter 2nd number: » ) ;
number2 = scan. nextInt ( ) ;
sum = addition ( number1, number2 ) ;
System . out . println ( «Sum = » + sum ) ;
}
}
The complete code and its respective output will be something like this:
From the above output, it is clear that there is no need to create the object of the class to call a static method instead it can be accessed directly within the class.
How to Access Public Methods
Now let’s consider the below example to test whether a public method can be accessed directly or not:
public int addition ( int num1, int num2 ) {
int add = num1 + num2 ;
return add ;
}
public static void main ( String [ ] args ) {
int number1, number2, sum ;
Scanner scan = new Scanner ( System . in ) ;
System . out . print ( «Enter 1st number: » ) ;
number1 = scan. nextInt ( ) ;
System . out . print ( «Enter 2nd number: » ) ;
number2 = scan. nextInt ( ) ;
sum = addition ( number1, number2 ) ;
System . out . println ( «Sum = » + sum ) ;
}
}
All the code is the same as in the previous example except the access modifier, but this time we get an error as shown in the following code snippet:
To access a non-static function, first, we have to create the object of the class then we will be able to access the method of the class:
The above snippet verifies that when we call the non-static method with the help of a class object then it works appropriately and provides the error-free output.
How to Access a Method from a Different Class
We have seen that a static method doesn’t require any object to be called within the same class but what will happen when we have multiple classes? Will the static method be invoked directly in such a case? Let’s experiment with it!
Let’s consider we have two class: one class named “AddNumbers” which will hold the main method and the second one is “MyFunctions” class:
MyFunctions.java
package addnumbers ;
public class MyFunctions {
public static int addition ( int num1, int num2 ) {
int add = num1 + num2 ;
return add ;
}
}
AddNumbers.java
public static void main ( String [ ] args ) {
int number1, number2, sum ;
Scanner scan = new Scanner ( System . in ) ;
System . out . print ( «Enter 1st number: » ) ;
number1 = scan. nextInt ( ) ;
System . out . print ( «Enter 2nd number: » ) ;
number2 = scan. nextInt ( ) ;
sum = addition ( number1, number2 ) ;
System . out . println ( «Sum = » + sum ) ;
}
}
We call the addition function of the MyFunctions class from the main method of AddNumbers class:
Although the addition method is static but we still get an error when we try to access it directly. This is because the addition method is not in the same class. So, to access the method of some other class we have to create the object of that class irrespective of its access modifier i.e. static or public.
AddNumbers.java
public class AddNumbers {
public static void main ( String [ ] args ) {
int number1, number2, sum ;
Scanner scan = new Scanner ( System . in ) ;
System . out . print ( «Enter 1st number: » ) ;
number1 = scan. nextInt ( ) ;
System . out . print ( «Enter 2nd number: » ) ;
number2 = scan. nextInt ( ) ;
MyFunctions obj = new MyFunctions ( ) ;
sum = obj. addition ( number1, number2 ) ;
System . out . println ( «Sum = » + sum ) ;
}
}
This time we create the object of MyFunctions class in the main function of AddNumbers class and then we access the addition method with the help of that object:
Now the above snippet verifies that the error has gone, and with the help of the object of MyFunctions class we got the desired results.
Conclusion
The class/static method can be accessed within the class directly while accessing the public methods without creating the object is not possible. While, in the case of multiple classes, the methods will be accessible only with the help of class objects regardless of their access modifier. This write-up provides a comprehensive guide of what are class methods and how to access them from the same class and from a different class.
About the author
Anees Asghar
I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.