Java Learning Lesson 05

Source: Internet
Author: User

Method


* Definition: The encapsulation of a code fragment that implements a function.

* [modifier ...] return value type method name ([List of formal parameters]) {

The logic implemented in the method

}


* Parameter list: The method receives the receiving medium of the external incoming data.

* Return value: After the method executes, the returned value can be a base data type (int,float, etc.) or a composite data type (such as arrays, objects, and so on).

* If the method does not need to return any value, then our method returns the type write void.

Returning a value in the method requires a return.


* Formal parameter list:

When we define a method, to call the method, we must pay attention to the type and number of the parameters we pass to the method, must correspond to each (parameter can have 0 or more, multiple parameters to use "," separated).


Focus Point:

* Method names are consistent

* All parameter types and quantities in the formal parameter list are consistent. The naming of parameter variables is completely non-relational.

* The type of the return value can be a base type, or it can be a reference type .

* methods can no longer be declared in a method, that is, the methods in a class are tied.

public class bookdemo {public static void  Main (String[] args) {//uses a variable to hold the return value of the method, and if the return value of the method is not saved, the return value of the method is placed in a temporary space, and the memory space is freed after the method execution ends. String mybookname= choicebook (1); System.out.print ("The book you selected is:" +mybookname); Long page = pagecount (1); SYSTEM.OUT.PRINTLN ("Total" +page+ "page");} Public static string choicebook (int num) {string bookname;switch (num) {case 1: bookname =  "A Brief History of Time", ";break;case 2:bookname = ", "melancholy grocery store"; break;case 3:bookname  =  "Fortress Besieged" ";break;default:bookname = " "three of us"; Return bookname;} Public static long pagecount (int num) { long page;switch (num) {case 1:page= 558;break;case 2:page=387;break;case 3:page=465;break;default:page=307;} Return page;}} 

650) this.width=650; "Src=" https://s1.51cto.com/wyfs02/M01/A6/F5/wKioL1neLWuCTAUqAAAX_LzZQow733.png-wh_500x0-wm_ 3-wmp_4-s_1279486786.png "title=" Oc98]j_[jecdfi7%ef5r[pe.png "alt=" wkiol1nelwuctauqaaax_lzzqow733.png-wh_50 "/ >


Attention:


* Once the return type (non-void) of the method is explicitly specified, it is important to ensure that the final method can successfully return the data for our corresponding return type.

* About void return types

If you do not add the return statement actively, the return will be added automatically when you execute it. When implementing the method of void type, it is no problem to add a return actively.

Java pre-compilation features:

* For the transfer of method parameters, the base type passes the value. For reference types, a reference is passed. (The address is passed)

Pass an array type implementation sort

Public class arrayparameterdemo{    public static void main ( String[] args) {         int []arr=new int[]{ 12,90,67,45,78,23};         sortdemo (arr);                      }    public static void sortdemo (Int []arr) {         int temp=0;        for (int i=0;i< arr.length-1;i++) {           for (int j= (i+1);j< arr.length;j++) {            if (Arr[i]<arr[j]) {                temp=arr[i];                arr[i]=arr[j];                arr[j]=temp;              }            }          }          for (int  i=0;i<arr.length;i++) {              System.out.print (arr[i]+ ",");           }    }   }

650) this.width=650; "Src=" https://s2.51cto.com/wyfs02/M01/A6/F7/wKioL1nePkKweSf7AAAYGg7Y77Q727.png-wh_500x0-wm_ 3-wmp_4-s_2638977266.png "title="}A]IL8PQ$E$SXO{JZ (95nqw.png "alt=" wkiol1nepkkwesf7aaaygg7y77q727.png-wh_50 "/ >

Class:

* Declaration of class:

Class is defined by the keyword class, and the general format is: [Class modifier]class class name [Interface Name table]{

type member variable 1;

Type member variable 2;

......

Type member Method 1 (parameter list) {

Method Body 1

}

Type member Method 2 (parameter list) {

Method Body 2

}

......

}

User class: Contains the Order class (the user orders by the method in the Order Class)


Product Category

E-Class Products

Daily Necessities Goods

Home Appliance Products


Order class

Public class user {public static void main (String[] args) {        int num=2;       string productname =null; Product myproduct=new product (num);//Call constructor Myproduct.getproductname (num);                          order myorder=new order ();                 myorder.getorder ();   }}class product{int num; string productname;//Constructor Product (int numparm) {num=numparm;};/ /Get Product name Public void getproductname (int num)  {  switch (num) {               case 1:productname= "Electronic goods";             &nbsP;&NBSP;BREAK;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;CASE&NBSP;2: Productname= "Household goods";               Break;              case 3: Productname= "Home Appliance Products";              break;           }         &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("You have chosen:" +productName);}} The class order{    //compiler adds a default constructor   order () {  }     public void getorder () {    system.out.println ("Congratulations, your order is successful!!! ");}}


650) this.width=650; "Src=" https://s5.51cto.com/wyfs02/M00/A7/03/wKioL1nfG8DhiBuPAAAU3Uq40_0324.png-wh_500x0-wm_ 3-wmp_4-s_2580620995.png "title=") c]y$6xqqh[) 09yvmft{v4k.png "alt=" wkiol1nfg8dhibupaaau3uq40_0324.png-wh_50 "/ >

* About the scope of variables:


* Member variables:

Properties of the class


* Local Variables:

The variables defined in the method are either the formal parameters of the method.


* For the Java language, scope control is controlled by blocks.

Block concept: A pair of {} parcels, the code snippet is called a piece.


For variables defined within a block:

* For the current block, you can no longer define a variable of the same name, even if the type is different.

* For the current block, a variable is defined, and the variable defined in the block cannot be accessed outside the block


* If there is a block nesting:

* Then the variables defined by the outer block are accessible in the inner block.


Construction Method (constructor)


* Special method in the class, for the definition, its method name must be the same as the class name, and does not return any value, mainly cannot add void.

* In new (when creating an object), it must be called to construct the method. But if we don't add our own defined constructors, the compiler adds a default constructor:

Class name () {

}

* If we take the initiative to add a default constructor, then when creating the object, pass the new class name (); Will call the default constructor we added ourselves.

* When we actively add a constructor with a parameter list and do not actively add the default constructor, then pass the new class name (); You will encounter a compilation problem.


Method overloading

* For a method of the same name, with a different parameter list, we can find our specific method when we access it by invoking a method to pass in the various parameter lists.


* When we define multiple overloaded methods, at compile time, the compiler can distinguish different methods according to the number of parameters and types of our method, and the execution phase can

It is not considered overloaded to have a different return value type, depending on the parameter list passed in when we call.

Practice:

Defines a class that has a member variable (short) of a 1-d array. Provide two methods, the first method accepts an int array, and the second method accepts an array of type long.

Both methods sum the values of the elements in the array in which the respective parameters are passed in. And with itself our class member variable array and make a difference. This result is eventually returned.

public class arrayoverload {    short []arrshort;     int sum;    public static void main (String[] args) { Arrayoverload array = new arrayoverload (5);                  int sum1=array.getarrplus (new int[]{ 1,2,3,4,5}); Long sum2=array.getarrplus (new long[]{1,2,3,4,5}); array. Arrayoverload (); The result of System.out.println ("Getarrplus (Int[] arr)" is +SUM1); System.out.println ("Getarrplus (Int[] arr) result is" +sum2 ");     arrayoverload (int a) {    arrshort = new short[ ]{1,2,3,4,5};    for (int i=0;i<arrshort.length;i++) {    sum+= Arrshort[i];    }    }    void arrayoverload ( ) {}    int getaRrplus (Int[] arr) {int sum3=0;for (int i=0;i<arr.length;i++) {sum3+=arr[i];} Return sum3 - sum;} Method name is the same, parameter type, number of different long getarrplus (Long[] arr) {long sum3= 0;for (int i=0;i<arr.length ; i++) {sum3+=arr[i];} Return sum3-sum;}}

650) this.width=650; "Src=" https://s4.51cto.com/wyfs02/M01/A7/08/wKioL1nfXlDgwOLsAAAZH9qEj3g421.png-wh_500x0-wm_ 3-wmp_4-s_2608975442.png "title=" 9y75_@57zy%jt{g{vqu~f5v.png "alt=" wkiol1nfxldgwolsaaazh9qej3g421.png-wh_50 "/ >



Java Learning Lesson 05

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.