Java method definition, calling and overloading methods
Definition and calling of methods
What is a method
A method is a piece of code used to complete a specific function, similar to functions in other languages.
Methods are used to define the behavioral characteristics and functional implementation of this class or instances of this class. Methods are abstractions of the behavioral characteristics of classes and objects. Methods are very similar to functions in procedure-oriented programming. In process orientation, function is the most basic unit, and the entire program is composed of function calls. In object-oriented, the basic unit of the entire program is a class, and methods are subordinate to classes and objects.
Method declaration format
[Modifier 1 Modifier 2 …] Return value type method name (formal parameter list) {
Java statement;… ; … … }
Method calling method
Object name.Method name (actual parameter list);
Method’s Detailed description
Formal parameters: Used to receive data incoming from the outside when the method is declared.
Actual parameters: the data actually passed to the method when calling the method.
Return value: The data returned by the method to the environment that called it after completion of execution.
Return value type: The data type of the return value agreed in advance. If there is no return value, it must be explicitly specified as void.
Note: Everything in Java is passed by value
For example: we want to print a number from 1 to n. The traditional writing method is written in the main method, but when there are many When there is a value, you have to write multiple for loops, so the code becomes more repetitive.
public class TestCode02 { public static void main(String[] args) { int n1 = 10; for (int i = 1; i <= n1; i++) { System.out.print(i + " "); } System.out.println(); //当有多个n时,都要每次写一遍for循环 int n2 = 13; for (int i = 1; i <= n2; i++) { System.out.print(i + " "); } System.out.println(); int n3=20; //for... } }
We extract the same code and put it in a method, so that we can call this method every time without having to write the same code every time
public class TestCode02 { public static void main(String[] args) { int n1 = 10; printNnums(n1); int n2=12; printNnums(n2); int n3=14; printNnums(n3); } public static void printNnums(int n){ for (int i = 1; i <= n; i++) { System.out.print(i + " "); } System.out.println(); } }
In this way, we have multiple n, just call the method once
Summary
1. The method is: extract the specific function to form a code snippet. This code snippet is what we call a method
2. Methods and methods are in a parallel relationship, so the methods we define cannot be written into the main method
3. Method definition –> Format:
through ’ s ’ s through ’ through through through through through through use through through through through through through through ‐ ‐ ‐ ‐ ‐ to, and Code reusability
5. Summary method definition format:
Modifier:
public staticMethod return value type: The data type corresponding to the method's return value
Data type: It can be a basic data type (- byte
,
short ,
,long
,float
,double
,char
,boolean
) It can also be a reference data type Method name: Know the meaning of the name, the first letter is lowercase, and the rest follow camel case naming, eg: addNum, generally try to use English for naming
- Formal parameter list: formal parameters required when defining the method: int num1, int num2 --> Equivalent to telling the caller of the method: how many parameters need to be passed in, and what parameters need to be passed in Type of parameter; actual parameters: specific parameters passed in when the method is called: 10,20 -->
- Method body: specific Business logic code
- return method return value:
- If the method has a return value: return method return value, return the return value to the method If the
method at the call location has no return value: return can be omitted, and the return value type of the method is: void
When will there be a return value? When there is no return value? –>Look at the requirements
- 6. What should we pay attention to when defining methods?
- How to write a formal parameter list: define several parameters and what types they are—>Uncertain factors we will use as formal parameters of the method
- Does the method need to return a value? If so, what is the type of the return value?
- 7. What should you pay attention to when calling methods?
- How to pass in the actual parameters: how many parameters to pass in, what type to pass in
- Whether the method has a return value that needs to be accepted
- Method overloading
What is method overloading
Method overloading means that multiple methods with the same name can be defined in a class, but Methods with different parameters. When called, the corresponding method will be automatically matched based on different parameters.
Pay attention to the essence: the overloaded method is actually a completely different method, just with the same name!
Conditions that constitute method overloading
Different meanings: different formal parameter types, number of formal parameters, and different order of formal parameters
- Only different return values do not constitute method overloading; (for example: int add (int a, int b) {} and void add (int a, int b) {} do not constitute method overloading)
只有形参的名称不同,不构成方法的重载;(如:int add(int a){}与int add(int b){}不构成方法重载)
public class TestCode03 { public static void main(String[] args) { add(7,8); add(1.02,2.03); add(1,3,5); add(1,4,6,9); } //定义一个int型两数相加 public static void add(int a,int b){ System.out.println(a+"+"+b+"="+(a+b)); } //定义一个double类型的两数相加 public static void add(double a,double b){ System.out.println(a+"+"+b+"="+(a+b)); } //定义一个三个数相加 public static void add(int a,int b,int c){ System.out.println(a+"+"+b+"+"+c+"="+(a+b+c)); } //四数相加 public static void add(int a,int b,int c,int d){ System.out.println(a+"+"+b+"+"+c+"+"+d+"="+(a+b+c+d)); } }
总结
方法的重载:在同一个类中,方法名相同,形参列表不同的多个方法,构成了方法的重载。
方法的重载只跟:方法名和形参列表有关,与修饰符,返回值类型无关。
注意:形参列表不同指的是什么?
(1)个数不同
add() add(int num1) add(int num1,int num2)
(2)顺序不同
add(int num1,double num2) add(double num1,int num2)
(3)类型不同
add(int num1) add(double num1)
The above is the detailed content of Java method definition, calling and overloading methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
