Calling a Non-void Method
Calling a Non-void Method
Understanding Non-void Method Calls
- A non-void method is one that returns a value after it has executed its functionality.
- You call a non-void method similarly to a void method, but you can store the return value in a variable or use it directly.
Defining a Non-void Method
- When defining, the name of the method should be preceded by the data type of the value it returns.
- For instance, a method returning an integer would be defined as
public int MyMethod() {...}
- A method can return any type of data including common types such as int, double, String, boolean, and even objects
Returning a Value
- A return statement is used within a non-void method to send a value back to the code that called the method.
- A return statement is typically written as
return expression;
- Where expression matches the type specified in the method’s declaration.
Implementing Returned Values
- When calling a non-void method, you need to have a way to capture the returned value. This is usually done by assigning the call to a variable.
- For instance,
int result = MyMethod();
Usage of a Non-void Method
- The returned value can be used directly in an expression like
total = price * MyMethod();
- It can also be used in control structures such as if statements, for instance
if(MyMethod() > 0) {...}
Method Calling Syntax
- To call a non-void method, you need an instance of the class (an object) in which the method is defined.
- The syntax for calling a non-void method is
object.MethodName(parameters);
where parameters are the input values required by the method. - Remember, the object used to call the method is also the one it will operate on and potentially alter.
Wrapping Up
- Understanding how to call a non-void method is essential to mastering object-oriented programming. They enable data to flow seamlessly between different parts of a program, enhancing modularity and readability.