Java call function in class

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.

Источник

How to Call a Method in Java

This article was co-authored by wikiHow staff writer, Travis Boylls. Travis Boylls is a Technology Writer and Editor for wikiHow. Travis has experience writing technology-related articles, providing software customer service, and in graphic design. He specializes in Windows, macOS, Android, iOS, and Linux platforms. He studied graphic design at Pikes Peak Community College.

This article has been viewed 709,819 times.

When beginning programming in Java, there are many new concepts to learn. There are classes, methods, exceptions, constructors, variables, and more, and it can become overwhelming. So, it is best to learn piece by piece. This wikiHow teaches you how to call a method in Java.

Image titled 972649 1

public static void methodName()  System.out.println("This is a method"); > 

Image titled 972649 2

  • Public: By placing the access modifier «public» before the method name allows the method to be called from anywhere.
  • Protected: The «protected» access modifier, only allows the method to be called within it’s class and subclasses.
  • Private: If a method is declared private , then the method can only be called inside the class. This is called the default, or package-private. This means that only the classes in the same package can call the method.

Image titled 972649 3

  • If the keyword «static» was not used, then the method can be invoked only through an object. For instance, if the class was called «ExampleObject» and it had a constructor (for making objects), then we could make a new object by typing «ExampleObject obj = new ExampleObject();», and call the method with using the following: «obj.methodExample();».

Image titled 972649 4

Image titled 972649 5

Declare the method name. After you’ve declared the classes that can access the method, the class it belongs to and the return value, you need to give the method a name so that it can be called. To give the method a name, simply type the method name followed by an open and closed parenthesis. The examples above include, «someMethod()» and «methodName()». You would then input all the method statements inside opened and closed curly brackets «<>«

Image titled 972649 6

public class className  public static void methodName() System.out.println("This is a method"); > public static void main(String[] args)  methodName(); > > 

Image titled 972649 7

Add a parameter to a method (if needed). Some methods require a parameter such as an integer (a number) or a reference type (such as the name of an object). If a method requires a parameter, you just simply type the parameter in between the open and closed parenthesis after the method name. A method that requires an integer parameter of an integer would look like «someMethod(int a)» or similar. A method that has uses a reference type would look like «someMethod(Object obj)» or similar.

Image titled 972649 8

Call a method with a parameter. When calling a method that requires a parameter, you would just simply add the parameter in the parethesis after the method name. For example:»someMethod(5)» or «someMethod(n)» if «n» is an integer. If the method requires a reference object, simply enter the name of the object in the open and closed parenthesis. For example, «someMethod(4, thing)».

Image titled 972649 9

public class myClass  public static void sum(int a, int b) int c = a + b; System.out.println("The sum of A and B is "+ c); > public static void main(String[] args)  sum(20, 30); > > 

Community Q&A

You create objects by invoking the constructor of their class (it has the same name as the class). Java already has some classes; for example, Integer, but you can also define your own class. For example, if you defined a class Orange, you could create an object of that class like this: «Orange o = new Orange();».

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

The main is what runs first, so make sure you call the second method from inside the main < >, and it will execute by itself.

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

A method is a set of code that is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name.

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

When calling a method that returns something, you can call another method based off of what that method returns. Let’s say we have a method called getObject() that returns an object. Well, in the class Object , there is a non-static method call toString that returns the Object in the form of a String . So, if you wanted to get that String from the Object returned by getObject() in one line, you just would write » String str = getObject().toString(); «.

Be careful about abstract classes and methods. If a method is abstract, it cannot be used until it is implemented by another class. This is because an abstract method doesn’t have any code in it in the first place. Abstract classes are used as a sort of framework.

You Might Also Like

Check Your Java Version in the Windows Command Line

Use Easy Windows CMD Commands to Check Your Java Version

Set Java Home

How to Set JAVA_HOME for JDK & JRE: A Step-by-Step Guide

Do Division in Java

How to Do Division in Java (Integer and Floating Point)

Compile and Run Java Program by Notepad

How to Compile and Run Java Programs Using Notepad++

Compile & Run Java Program Using Command Prompt

Calculate Percentage in Java

Add JARs to Project Build Paths in Eclipse (Java)

Check Null in Java

Install Java in Ubuntu Using Terminal

Program in Java

Create an Executable File from Eclipse

Update Java

Print Double Quotes in Java

Simple Steps to Type a Bunny with Your Keyboard

Create a New Java Project in Eclipse

About This Article

This article was co-authored by wikiHow staff writer, Travis Boylls. Travis Boylls is a Technology Writer and Editor for wikiHow. Travis has experience writing technology-related articles, providing software customer service, and in graphic design. He specializes in Windows, macOS, Android, iOS, and Linux platforms. He studied graphic design at Pikes Peak Community College. This article has been viewed 709,819 times.

1. Declare the access of a method (i.e. public, protected, private).
2. Declare the class the method is in (i.e. static).
3. Declare the return value of the method (i.e. void, int).
4. Declare the name of the method followed by open and closed parenthesis.
5. Add parameters (arguments) in the parenthesis separated commas.
6. Call the method by typing the name of the method followed by parenthesis.

Is this article up to date?

Quizzes

You Might Also Like

Use Easy Windows CMD Commands to Check Your Java Version

How to Set JAVA_HOME for JDK & JRE: A Step-by-Step Guide

How to Do Division in Java (Integer and Floating Point)

How to Compile and Run Java Programs Using Notepad++

Источник

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:

Источник

Читайте также:  Https sdo dposoc ru local crw course php id 361
Оцените статью