[Java getting started notes] Object-Oriented Programming BASICS (2): detailed methods, java Object-Oriented Programming

Source: Internet
Author: User

[Java getting started notes] Object-Oriented Programming BASICS (2): detailed methods, java Object-Oriented Programming
What is a method? Introduction

In the previous blog, we learned that methods are an integral part of classes and abstract behavior features of classes or objects.

Methods are similar to functions in terms of syntax and function. However, methods are different from traditional functions:

In a structured programming language, a function is a basic component of a program. A program is composed of functions;

In object-oriented programming languages, classes are the basic unit of a program. Methods belong to Classes or objects and cannot exist independently;

The features of methods in Java are mainly in the following aspects:

Methods cannot exist independently. methods can only be defined in classes and belong to a class or object;

Methods cannot be executed independently. classes or objects must be used as callers;

Methods. in Java, methods are classified into the following types:

Methods in Java can be divided into constructor methods and common methods, while common methods can be divided into class methods and object methods;

Method Definition

In the previous blog, we already know how to define the method. Let's review it again:

Constructor:

[Modifier] Class Name ([parameter name]) {// Function Code}

 

A constructor is a special method. It has two differences with a common method: The method name must be the same as the class name, and it has no return value.

Common method:

[Modifier] Return Value Method Name ([parameter name]) {// Function Code}

 

We can see that the structure of common methods is mainly divided into five parts,

Modifier: Set the access permission of the method, which can be public, protected, private, or not specified;

Return Value: The content returned after the method is called. It can be a basic data type, a reference type, or no return value. If no return value is returned, void is used.

Method Name: a custom identifier. It is mainly used for calling. It is used for calling external or non-subclass classes. method name or object name. Method Name

Parameter: the parameter to be passed when the method is called. There can be 0 or more parameters.

Method body {}: code used to define the implementation function in the method body

 

Let's take a complete example:

Define a Person class:

Public class Person {// defines a Person class public String name; // String type attribute name public int age; // int type attribute age public Person (String n, int a) {// constructor. There are two parameters n and a. If an object is created and this constructor is called, The name attribute is set to the passed n, age is. Name = n; age = a;} public void showName () {// common method. The main function is to display the name System of the object. out. println ("My name is" + name);} public void setAge (int a) {// common method, the main function is to set the object age, there is a parameter, set the age of the object to the passed a variable age = a;} public int getAge () {// normal method. There is a return value that returns the age return age of the object ;}}

 

Usage:

Public class Test {public static void main (String [] args) {Person p = new Person ("Zhang San", 20); // instantiate an object and call the constructor, two parameters are passed, and the parameters are set to the object's name attribute and age attribute p. showName (); // call the showName method of the p object, execute the code in the method body, and print the name p of the p object. setAge (25); // call the setAge method of the p object and reset the age attribute value of the p object to 25 int pAge = p. getAge (); // call the getAge method of the p object. This method has a return value. The age attribute value of the p object is returned and the return value is assigned to the pAge variable }}

 

Mechanism of calling methods and passing parameters in memory

The program won't be a good cook at all points. Let's take a look at what the call and parameter passing of methods look like in the memory of the program running:

If you are interested in the JVM running mechanism, refer to the following articles:

Memory Allocation during java Runtime

Deep understanding of JVM-JVM Memory Model

Notes on deep understanding of Java Virtual Machine

Java runtime memory distribution chart

Of course, we recommend that you read a good book "deep understanding of Java Virtual Machine" if you are interested in and have basic knowledge of children's shoes.

Let's take a look at the code in the above example:

Person p = new Person ("Zhang San", 20 );

The Analysis of object creation is analyzed in the previous blog. If you are interested, you can view the following content: [Java entry notes] Object-Oriented Programming BASICS (1): class and object at the end.

After an object is created, it looks like this in the memory:

 

The program continues to run down:

P. showName ();

Call the showName method of the p object and execute the Code:

Println is also a method, which is defined in Java API. It is a bit difficult to execute in memory. Now, let's not look at this. After executing this sentence, print out "My name is James"

Continue to run

P. setAge (25 );

Call the setAge method of the p object

After performing this step, we find that this method has an int-type parameter named a and its value is 25.

Continue to execute the setAge method and assign the value of a to age

In this case, the age property value of the p object changes to 25. After the method is executed, clear the reference of the completed Code and continue the following code.

Int pAge = p. getAge ();

Executing this statement will return the age of the p object and assign the value to the int type variable pAge. Therefore, the pAge value is also 25:

 
What is method overloading?

Method overloading refers to defining multiple methods with the same name in a class, but each method must have different parameter types or number of parameters. When calling an overloaded method, the Java compiler can select an appropriate method by checking the parameter type and number of called methods. Method Overloading is usually used to create a method that completes a set of similar tasks but has different types or numbers of parameters.

How to implement method overloading?

Method overloading requires two different methods, three of which are not affected. Two of them refer to the same method name in the same class. One difference is that the method parameters are different, the differences mainly refer to the differences in the number, type, and location of parameters.

The two are not affected:

Different modifiers do not affect method overloading.

The type of the return value of a method cannot be used to identify the overload of a method. That is to say, no matter whether the return value is the same or different, it does not affect whether the method is overloaded or not.

The name of a parameter cannot be used to identify whether a method is overloaded. That is to say, if the type and number of the parameters are the same and only the names of parameters are different, the parameter does not constitute an overload.

Overload of constructor:

Constructor is also a method type, which can also be overloaded and follow the above rules.

Example:

Public class Person {public String name; public int age; public Person () {} public Person (String n, int a) {name = n; age = a} public void setInfo () {name = "zhangsan"; age = 20;} public void setInfo (String n) {name = n ;} public void setInfo (int a) {age = a;} public void setInfo (String n, int a) {name = n; age = a;} public void setInfo (int, string n) {name = n; age = ;}}

 

 

 

Both the above two constructor methods and four setInfo methods are overload methods, because they meet the requirements of overload: the same method name in the same class, different parameter types or numbers.

If the following method is added in the preceding example, it is not overloaded:

Private int setInfo () {}// modifier is different from the return value, but there is already a setInfo method without parameters above, so it is not a heavy load

Public void set () {}// different method names, not reload

Public void setInfo (int B) {}// the parameter names are different. The types are the same and are not overloaded.

 

Use of overload methods:

Public class Test {public static void main (String [] args) {Person p1 = new Person (); Person p2 = new Person ("Li Si", 30 ); // when the two objects are instantiated, the first one does not pass the parameter. Therefore, the first constructor is called and the second one has two parameters. Therefore, the second constructor p1.setInfo () is called (); // if there is no parameter, call the first setInfo method p1.setInfo (""); // if there is a String type parameter, call the second setInfo method }}

 

 

Variable number of parameters

If we are implementing a method and we are not sure how many parameters a method has, how should we define this method?

For example, if we want to write a method to implement addition, instead of simply adding two numbers, we need to add them together no matter how many numbers there are, how should we define this method? Obviously, it cannot be well implemented by defining or reloading in a common form, but we can define this method using an input parameter passing method added after jdk1.5.

Example:

public class Operation{    public static int add(int... num){        int result = 0;        for(int i = 0; i < num.length; i++){            result += num[i];        }        return result;    }}

 

In this example, we can see that the method for defining a variable parameter only needs to add three vertices after the type, when this method is called, multiple parameters of the same type can be passed.

When using the num parameter, we can see that it is used in the form of an array. Therefore, this variable parameter is essentially an array, but it is convenient to call it, see:

Public class Test {public static void main (String [] args) {Operation ope = new Operation (); ope. add (1, 2); // calculate 1 and add 2 ope. add (3, 4, 5); // calculate 3 plus 4 plus 5 }}

 

We do not need to create another array object when using it.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.