Calling methods in class java

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 .

Читайте также:  Python rfind in string

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:

Источник

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,612 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

Источник

How to call a method from another class in java?

The method of the class can be default, public, static, protected, and private. A method can be called from another class using the object.

Calling a default method from another Class

If the method does not have any modifier, it is taken as default. When the method is a default method, it can be accessed only within the package but it cannot be accessed outside the package.

The default method provides more accessibility than private but is more restrictive than protected and public.

class Bird < public void printName() < System.out.println("Smallest bird is: Hummingbird"); >> public class Animal < public static void main(String[] args) < // creating object of class Bird Bird obj = new Bird(); // calling method printName of class Bird obj.printName(); >>
Smallest bird is : Hummingbird

Calling a static method from another Class

The static method can be accessed directly by class name without creating an object of that class. A static method can access static data directly but requires an object to access instance.

The example program below illustrates how to call a static method from another class.

class Star < static void printInfo() < System.out.println("Our galaxy name is : Milky way galaxy"); >> public class Galaxy < public static void main(String[] args) < // calling a static method by Class name Star.printInfo(); >>
Our galaxy name is : Milky way galaxy

Calling a public method from another Class

A public method of a class can be accessed by creating an object of that class. The public method can be accessed by another class.

The public method can be accessed within the package and outside the package also.

The example program below illustrates how to access the public method from another class.

class Student < public void Name() < System.out.println("Student name is : Joe"); >> public class School < public static void main(String[] args) < // creating object of Class Student Student st = new Student(); // calling Name method of Student class st.Name(); >>

Calling a protected method from another Class

A protected method can be called in another Class only if that Class is a sub-class of the Class which contains the protected method.

The method can be accessed by creating an object for the subclass. The protected method provides more accessibility than private method.

The example program below illustrates how to access protected method from another Class.

class Staff < protected void getName() < System.out.println("Teacher name is : Alice"); >> public class Teacher extends Staff < public static void main(String[] args) < // creating an object of Class Teacher Teacher t1 = new Teacher(); // calling getName() method of Class Staff t1.getName(); >>

Calling a private method from another Class

A private method can be called from another Class by using reflection API. A private method has more accessibility restrictions than other methods.

A private method can be accessed from another class using getDeclaredMethod(), setAccessible() and invoke() methods of the java.lang.class and java.lang.reflect.Method.

The example program below illustrates how to access a private method from another Class.

import java.lang.reflect.Method; class Demo < // Private method private void printData() < System.out.println("Private Method called from another Class"); >> public class Example < public static void main(String[] args) throws Exception < Demo d = new Demo(); // Using getDeclareMethod() method Method m = Demo.class.getDeclaredMethod("printData"); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(d); >>
Private Method called from another Class

Источник

Оцените статью