Basic structure of Java class (partial)

Source: Internet
Author: User
Tags modifier modifiers

Basic body of Java class (partial)

Before you learn this part of the knowledge, you need to understand some abstract concepts: classes, objects, properties, methods (functions).

For the sake of understanding, we use an example to understand these concepts. We often say that human beings, then all the people belong to a class, that is human, human is a very broad concept, specific to a person such as Zhang San, is a human group of a specific person, that is, the object; Zhang San will have their own name, gender, age and so on their own labels, these tags are the attributes we say At the same time Zhang San in daily life there will be many behaviors: eating, drinking, playing and so on, these behaviors we call the method (function).

A: Through this example, we are not difficult to summarize the following points:

1: A class is a collection of objects with the same properties and behavior

Each of us has its own name, gender, age, etc. to mark the attributes of each person, our daily behavior will have the same part, so a large number of people together to form a class: human.

2: What is the relationship between classes and objects?

Classes define the properties and methods of an object, and properties and methods are the object's essence.

3: What is the role of the class?

A class is a template that defines properties and methods that are common to multiple objects.

In the actual development process, we need to first create a class, then instantiate the object, thus calling its methods, to achieve our goal, while in the analysis process, we usually to a particular object to analyze, analyze its properties and methods, and then to classify.

Second: The first thing you need to know is how to create a class. The format is as follows:

[Access modifier] [Modifier] class class name {class Body}

Specific code: This creates a Personaccount class that declares its properties in code.

class personaccount{// Declaration attributes (account number, password, balance)        String accountId = "123456789";         = "123456";         Double balance;}

Three: Learn to create a class, and then learn how to create a method. The format is as follows:

[Access modifier] [modifier] Return value type method name (formal parameter list) {//formal parameter is what we usually call a variable, but to add a variable type, the middle of multiple variables separated by commas

Execute the statement;

return value;//If you need to get a value from this method, you need to return with a void when you don't need a value

}

Specific code: We have created a method to view the ID in the Personaccount class, we do not require access modifiers and modifiers at the beginning of the study, so we can omit them and learn later.

// View ID  (method)         String Getaccountid () {            return  accountId;         }

It is important to note that a method can be called, but another method cannot be defined in a method.

    • Overloads of the method:

In Java, methods that have the same name and different parameters in the same scope (class) Form a method overload.

Three main principles:

1: The method (function) has the same name, 2: Different parameters (including quantity, type, order); 3: Same scope (Class).

Note: Only the return value types are different and do not constitute method overloads.

Cases:

void Fun (int  x) {...} int  Fun (int

The above two methods do not constitute a method of overloading, we can think, when we call the fun method, the system at this time do not know which method to go to execute, will be an error. Therefore, only the return value type differs from the overload that does not constitute a method. It is important to note that the overloads of a method have nothing to do with the type of the return value. So what's the point of the return value being there? It can be understood that, depending on the specific development instance, the presence of the return value exists to accommodate specific business requirements. In addition, the overloads of the method must be for methods with the same function, the methods of different functions must not be overloaded with methods.

Cases:

// Deposit (need to know the amount of deposit)        void Deposit (double  amount) {            = balance + amount;        } // deposit, Current        void Deposit (double amount,int term ) {            = balance + amount;        } 

The above two methods are to deposit this method of overloading, in the process of execution, I only need to pass this method to the parameter, such as 1:deposit (10000) 2:deposit (10000,12), The first statement Hu automatic root method name and the condition of the formal parameter automatically match the corresponding method, will call void Deosit (double amount) {} This method, then the second statement will go to the following method. In other words, when we overload the method, we only need to pass it the parameter, that is, to give the method the specific parameters, the system compiler will automatically according to the type and number of parameters and order to enter their corresponding function. It can be said that Java is a very smart and advanced programming language.

    • Construction method

The construction method is created to instantiate a class, that is, to create an object. Two major features: 1: The method name must be the same as the class name; 2: no return value type

To use a class, which is essentially a method of using one of these objects, we must first create an object, and we need to construct the method.

[Access modifier] Method name (formal parameter list) {method body}

The method body of the beginner stage is usually the initialization of the attribute (giving the initial value), that is, the instantiation of the class.

Cases:

 Public classcar{PrivateString color; Private DoublePrice ;  PublicCar () {//This is a constructor method with no return value type, and the method name is consistent with the class name.             }     Publiccar (String color) { This. color = color;//This is used here to differentiate form parameters, which represent properties in a class    }     PublicCar (String color,DoublePrice ) {         This. color =color;  This. Price =Price ; }    }

Finally put a complete code for reference only, understanding learning.

 PackageLF; //Create a personal account class        classpersonaccount{//declaring attributes (account ID, password, balance)String accountId = "123456789"; String pwd= "123456"; Doublebalance;//View ID (method)String Getaccountid () {returnaccountId; }//Change Password (no return value required)        voidsetpwd (String newpwd) {pwd=newpwd; }//View Balance (method)        DoubleGetBalance () {returnbalance; }//Deposit (need to know the amount of deposit)        voidDepositDoubleamount) {Balance= Balance +amount; }//deposit, Current, deposit method of overloading        voidDepositDoubleAmountintTerm ) {Balance= Balance +amount; }            }
 PackageLF; Public classTestaccount { Public Static voidMain (string[] args) {/*** System Default Construction Method statement * Personaccount () {*} * Write or not write, this method of construction exists*/Personaccount account1=NewPersonaccount ();//create an object of the Personaccount class://Call the Getaccountid () method in Account1 to get the IDSYSTEM.OUT.PRINTLN ("Account1 ID is:" +Account1.getaccountid ()); //Call the GetBalance () method in Account1 to get the balanceSystem.out.println ("Account1 's balance is:" +account1.getbalance ()); Account1.deposit (10000);//Call Deposit Method Deposit $10000//Call the GetBalance () method in Account1 to get the balance after depositSystem.out.println ("The balance of account1 after deposit is:" +account1.getbalance ()); System.out.println ("Account initial password is:" +account1.pwd); }}

  

  

Basic structure of Java class (partial)

Related Article

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.