The class in Day12-java--DAY10

Source: Internet
Author: User
Tags define local modifier pow

First, the user custom class

1, write first a simple employee class as an example of the description.

The code is as follows:

1 Importjava.time.LocalDate;2 3 /**4 * Custom Method Exercise--Test this program contains two classes of employee class and Employeetest class with public modifier5  * 6  * @author: Archer-lcy7 * @date: February 3, 2018 PM 8:08:518  */9  Public classEmployeetest {Ten      Public Static voidMain (string[] args) { One         //define an employee class and assign a value AEmployee staff[] =NewEmployee[3]; -System.out.println ("Pre-pay"); -Staff[0] =NewEmployee ("Herry", 70000, 1988, 12, 3); theSTAFF[1] =NewEmployee ("Marry", 20000, 1990, 1, 31); -STAFF[2] =NewEmployee ("Amy", 10000, 1989, 11, 23); -  -         //give everyone a raise of 5% and print +System.out.println ("After a pay raise"); -          for(Employee em:staff) { +Em.raisesalary (5); ASystem.out.println ("Name:" + em.getname () + "T-Salary:" + em.getsalary () + "\ T entry time:" +em.gethireday ()); at         } -     } - } -  - /** - * Employee Class in  *  -  * @author: Archer-lcy to * @date: February 3, 2018 PM 8:28:40 +  */ - classEmployee { the     PrivateString name; *     Private Doublesalary; $     PrivateLocaldate Hireday;//Localdate need to import package java.time.LocalDate;Panax Notoginseng  -      PublicEmployee (String name,DoubleSalaryintYearintMonthintDay ) { the         Super(); +          This. Name =name; A          This. Salary =salary; the          This. Hireday =Localdate.of (year, month, day); + output (); -     } $  $     //Output -      Public voidoutput () { -System.out.println ("Name:" + name + "\ t Salary:" + salary + "T-entry time:" +hireday); the     } - Wuyi      PublicString getname () { the         returnname; -     } Wu  -      Public Doublegetsalary () { About         returnsalary; $     } -  -      Publiclocaldate Gethireday () { -         returnHireday; A     } +  the      Public voidRaisesalary (Doublebypercent) { -         Doubleraise = This. Salary * bypercent/100; $Salary + =raise; the     } the}

Attention:

(1) In this example, there are two classes, one is the employee class, and the other is the Employeetest class with the public access modifier. Where the Employeetest class contains the main method.

(2) The source file name is Employeetest.java, because the file name must match the name of the public class. In a source file, there can be only one common class, but the number of non-common classes may be arbitrary.

(3) When compiling this source code, the compiler will create two class files in the directory: Employeetest.class and Employee.class.

(4) The program contains the class name of the main method to provide the bytecode interpreter, in order to start the program: Java employeetest, bytecode interpreter began to run the code of the Main method of the Employeetest class. In this code, an array of employee classes is defined, with three groups, each of which constructs three new employee objects and displays their status.

2. Use of multiple files

In Employeetest.java a source file contains two classes. In general, however, we are accustomed to placing each class in a separate source file. For example, put the Employeetest class in Employeetest.java and the employee class in Employee.java.

If you are accustomed to the above mentioned method of organizing files separately, you can use the following three ways to compile the source program:

Note: Remember to use dir to view the current directory each time before using the command prompt window to avoid unnecessary embarrassing errors. It is also important to note that Javac and Java must be in the directory where the files are located, such as:

(1) Use wildcards to invoke the Java compiler: Javac Employeetest*.java, at which point all source files that match the wildcard are translated into class files. The successful compilation results are as follows:

(2) The second is used: Javac Employeetest.java, the successful results of the compilation are as follows:

(3) The third type: If you want to use the standalone test: Java employeetest This method can print the results in a command prompt window, as shown in the following:

A part of a larger application that can be used): Java application

3. Analysis of employee category

(1) There is a constructor and a 5 method in this class:

/** Constructor */

Public Employee (String name, double salary, int year, int month, Int. day)

/**5 a method */

public void output ()

Public String GetName ()

Public double getsalary ()

Public Localdate Gethireday ()

public void Raisesalary (double bypercent)

(2) All methods are marked with public. The keyword public means that any method of any class can invoke these methods.

(3) There are 3 sample fields in the Employee class to hold the data that will be manipulated:

private String name;

private double salary;

Private Localdate Hireday;

(4) The keyword private ensures that only the employee class itself can access these instance domains, and that the methods of other classes do not.

(5) Note: You can have public to mark instance fields, but this is a highly discouraged approach. The public data domain allows any method in the program to read and modify it, which destroys the encapsulation. Any method of any class can modify public with, which means that some code will be able to use this access permission, which we do not want to see.

(6) Note: There are two instance fields that are objects themselves: the Name field is an object of the string class, and the Hireday field is an object of the Localdate class. In fact, this is a common scenario: Classes typically include instances of types that belong to a class type.

4, the use of the constructor function

A. Starting analysis from the constructor of the employee class

Public Employee (String name, double salary, int. year, INT month, Int. day) {

Super ();

THIS.name = name;

This.salary = salary;

This.hireday = Localdate.of (year, month, day);

Output ();

}

(1) You can see that the constructor is the same as the class name, and when you construct an object of the employ class, the constructor runs to initialize the instance domain to the desired state.

(2) For example: New Employee ("Herry", 70000, 1988, 12, 3); This code, when creating an instance of the employee class, will set the instance domain to: name= "Herry"; salary=70000;hireday= Localdate.of (1988,12,3);

(3) Unlike other methods, a constructor is always called with the execution of the new operator, and a constructor cannot be called on an existing object to achieve the purpose of a new invocation. For example: Herry.employee ("Herry", 70000, 1988, 12, 3); A compilation error is generated.

4. Implicit parameters and Explicit parameters

Implicit parameter: Appears before the method name.

Explicit arguments: In parentheses after the method name.

Methods are used to manipulate objects and to access their instance domains. Set the salary instance field of the object calling this method to the new value. For example: Method:

public void Raisesalary (double bypercent) {

Double Raise =salary *bypercent/100;

Salary +=raise;

}

In each method, the keyword this represents an implicit parameter. The above method can be written in the following way: (The advantage: This allows you to distinguish the instance field from the local variable)

public void Raisesalary (double bypercent) {

Double Raise =this.salary *bypercent/100;

Salary +=raise;

}

Note that implicit and parameterized constructs do not coexist: try to write out both the parameter structure and the default construct, and when you do not display the default constructs, the parameters are overwritten and the second time you use them.

For example: The left two groups are with default parameters, will not error, the right side is not with default parameters, will be error (red wavy line part)

In Java, all methods must be defined internally in the class, but not inline (inline) methods. Whether to set a variable inline method is a task for a Java virtual machine

5. Encapsulation

Encapsulation (encapsulation) is an important principle of object-oriented approach, which is to combine the object's attributes and operations (or services) into a separate whole, and to hide as much as possible the internal implementation details of the object.

Encapsulation is the process and data is surrounded, access to data only through the interface defined. Object-oriented computing begins with this basic concept that the real world can be portrayed as a series of fully autonomous, encapsulated objects that access other objects through a protected interface. Encapsulation is an information hiding technology that is encapsulated in Java through the keyword private,protected and public.

Advantages: (1) Once set in the constructor, there is no way to modify it, so as to ensure that it will not be destroyed, increased safety factor.

(2) The converter can perform error checking, and the domain assignment directly will not have these processing.

6. Static method

The following scenarios are suitable for static methods:

(1) A method does not require access to the object state, and its required parameters are provided by explicit parameters (for example: Math.pow)

(2) A method only needs to access the static domain of the class

Static and Static methods in Java are functionally the same as C + +, unlike syntax writing. java. such as: Math.pow; C + + is accessed using:: operator, such as: Math::P I.

About "static": At first, c introduces the keyword static in order to represent a local variable that still exists after exiting a block in this case, the term "static" is meaningful; the variable persists and persists when you enter the block again. Then, Static has a second meaning in C that represents global variables and functions that cannot be accessed by other files. To avoid introducing a new keyword, the keyword static is reused. Finally, C + + reuses this keyword for the third time, completely different from what was previously given, which is interpreted as: variables and functions that belong to the class and are not part of the class object. This is the same meaning as in Java.

-------from "Java Core technology"

Second, the object construction

Constructor:

(1) Features: no return value (void is not), method name and class name are the same (method name, parameter is different, parameter can have 0 or 1 or more overloads of construction method), each class can have more than one constructor, the constructor is always called with the new operation

(2) can specify parameters and implement overloading

(3) Note: The Java constructor works the same way as C + +. However, all Java objects are constructed in the heap, and constructors are always used with the new operator. Employee number ("Herry", 70000, 1988, 12, 3);//is correct in C + +

(4) Warning!! : Do not define local variables with the same name as the instance domain in the constructor. For example

Public Employee (String N, double s, ...) {

String name = n;

Double salary = s;

}//is wrong.

In the above error example, the local variable name and salary are declared in this constructor. These variables can only be accessed inside the constructor. These variables mask instance fields of the same name.

Constructors that call the same class within a constructor can use the This keyword, this (...), such as:

Constructor Summary considerations:

(1) There can be more than one constructor in a class, which is the same as the class name, and when there are more than one constructed method, these methods pass different parameters.

(2) If there is no constructor in a class and there is no main method, this will default to a non-parametric construct; This constructor sets all instance fields to the default values, that is, the instance field, the numeric type is 0, the Boolean is false, and the object variable is null.

(3) If there is at least one constructor in the class and the constructor does not have parameters, then it is considered illegal to construct the object without supplying the argument.

(4) If the constructor does not display the value assigned to the instance field, it is automatically assigned the default value: The value is 0, the Boolean value is False, and the object reference is null. This can affect the readability of your code.

(5) Note: in C + +, the instance domain of the class cannot be initialized directly, and all domains must be set inside the constructor.

Three, the package

The main reason for using a package is to guarantee the uniqueness of the class name, and when two programmers have each created two classes of the same class name, there will be no conflict if the class is placed in a different package.

To ensure the absolute uniqueness of the package, Sun recommends that the company's Internet domain name (which is unique) be in reverse form as the package name. For example: banana.com, reverse turns to Com.banana.

From the compiler's point of view, there is no connection between nested packages.

A class can use all classes in a package, as well as public classes in other packages. There are two ways to access the public class in another package:

(1) Add the full package name (tedious) before each class name, for example: Java.time.LocalDate today =java.time.localdate.now ();

(2) Our usual method is to import the package using import, the import statement should be at the top of the source file (behind the packages statement), so that you do not need to prefix the preceding. For example: import java.time.LocalDate; this time can be used: Localdatetoday=localdate.now ();

When two packages contain the same class name, when used, the compiler does not recognize which class to use, and we can prefix the statements used. For example, when two different classes contain a date class, you can say this:

Note: In C-h, a namespace (namespace) is similar to the package mechanism. In Java, the package and import statements resemble the namespace and using directives in c+h.

Static import: such as: import static java.lang.system.*, this time can write Out.println (); However, this reduces the readability of the program.

Four, class design skills

1, to ensure the private data.

2, the data must be initialized.

3. Do not use too many private types in the class.

4. The duties of a class should not be too much or too little.

5, the class name and method name as much as possible to reflect their responsibilities.

6. Use immutable classes as a priority.

The class in Day12-java--DAY10

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.