Table of Contents
Definition and calling of methods
What is a method
Method declaration format
Method calling method
Method’s Detailed description
Summary
Pay attention to the essence: the overloaded method is actually a completely different method, just with the same name!
Conditions that constitute method overloading
总结
Home Java javaTutorial Java method definition, calling and overloading methods

Java method definition, calling and overloading methods

May 16, 2023 am 09:04 AM
java method

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...
        
    }
}
Copy after login

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();
    }
}
Copy after login

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 static

  • Method return value type: The data type corresponding to the method's return value

  • Data type: It can be a basic data type (
  • byte

    ,

    short
  • ,
int

,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));
    }
}
Copy after login

Java method definition, calling and overloading methods

总结

  • 方法的重载:在同一个类中,方法名相同,形参列表不同的多个方法,构成了方法的重载。

  • 方法的重载只跟:方法名和形参列表有关,与修饰符,返回值类型无关。

  • 注意:形参列表不同指的是什么?

(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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles