Java Core Technology (III)--Objects and classes (1)

Source: Internet
Author: User
Tags class definition

This article introduces the objects and classes of Java program Design in depth, mainly involves the following content:
-Object-oriented programming
-How to create a class object in a standard Java class library
-How to write your own class

1. OOP overview

Object-oriented programs are made up of objects, each containing a specific part of the functionality exposed to the user and a hidden implementation part. In OOP, you don't have to care about the specific implementation of an object, as long as you can meet the needs of users.
In OOP, the data is first, and then the algorithms that manipulate the data are considered.

Class 1.1

A class is a template or blueprint for constructing objects, and you can imagine a class as a cutting machine for making cookies and imagining objects as cookies. The process of constructing an object from a class is called creating an instance of the class.
(1) encapsulation (sometimes called data hiding), formally, is the combination of data and behavior in a package, and the object's users hide the way the data is implemented.
(2) The data in the object is called the instance domain , and the process of manipulating the data is called a method . There is a specific set of instance field values for each particular class instance, and the collection of these values is the current state of the object.
(3) The key to implementing encapsulation is that the methods in the class must not directly access the instance fields of other classes, and the program interacts with the object data only through the object's methods.

1.2 Objects

Use OOP to figure out the three main features of an object
-The behavior of the object--what actions can be applied to the object, that is, the method
-The state of the object-how the object responds when those methods are applied
-Object representation-how to identify different objects with the same behavior and state

Relationship between the 1.3 classes

Among the most common relationships between classes are
-Dependency (USES-A)--If a class's method operates on another class's object, it says one class depends on the other.
-Aggregation (HAS-A)--The actual inclusion relationship
-Inheritance (IS-A)--used to denote special and general relationships

2. Using predefined Class 2.1 objects and object variables

To use an object, you must first construct the object, set the initial state, and then apply the method to the object.
(1) In Java, a constructor is used to construct a new instance, and the constructor is preceded by the Add new operator.
The constructor is actually a special method. The name of the constructor should be the same as the name of the class.
Example of constructing an object of the data class and saving it in a variable

Data birthday = new Date ();

(2) The above example can see that the individual new data () is the construction of an object, the individual Data birthday is to define an object variable, the object and object variables differ greatly.
An object variable is not an object, nor does it actually refer to an object, so it is not possible to apply a method of any class date to that variable, but the object can.
So

Data birthday;
s = birthday.tostring ();

Is wrong,
and

System.out.println (New Data ());

And

String s = new Data (). toString ();

And

Date birthday;
Birthday = new Date ();
String s = birthday.tostring ();

are right.
(3) Therefore, it is necessary to realize that in Java, the value of any object variable is a reference to an object stored in another place. The return value of the new operator is also a reference, which is

Data birth = new data ();

The expression on the right side of the equal sign constructs an object of type date, and its value is a reference to the newly created object, which is stored in the variable birth.

2.2 GregorianCalendar Class

The standard Java class Library contains two classes: the Date class representing the point in time previously used, and the GregorianCalendar class for representing the calendar notation. While the latter extends to a more general Calendar class, it describes the general nature of calendars.
Although the date class has some other methods in addition to the methods used earlier, these methods may be deleted in the future class library version, have been marked as discouraged, and may still be used at compile-time warnings.
The GregorianCalendar class contains much more methods than the date class.

2.3 Change method and accessor method

The method of modifying an instance field is called a change method, and the method that accesses only the instance domain without modification is called an accessor method.
If the function of the above calendar is to provide a point in time of the year, month, day and other information, to query these settings information, you should use the GregorianCalendar class get method, if you want to modify, you need to set and add methods.
The usual habit is to prefix the accessor method name with get and prefix set before changing the method name.

3. User-defined class

Let's learn the various main classes required to design complex applications, usually without the main method, but with their own instance fields and instance methods.
To create a complete program, you should combine several classes, where only one class has the Main method.

In Java, the simplest class definition is in the form

Below, we write a simple employee class, and then we explain it in detail.

Importjava.util.*;/** * This program tests the Employee class. * @version 1.11 2004-02-19 * @author Cay Horstmann */
      Public  class employeetest{    Public Static void Main(string[] args) {//Fill the staff array with three Employee objectsemployee[] Staff =Newemployee[3]; staff[0] =NewEmployee ("Carl cracker.",75000,1987, A, the); staff[1] =NewEmployee ("Harry Hacker.",50000,1989,Ten,1); staff[2] =NewEmployee ("Tony Tester.",40000,1990,3, the);//Raise everyone ' s salary by 5%       for(Employee E:staff) e.raisesalary (5);//Print out information on all Employee objects       for(Employee E:staff) System.out.println ("Name="+ e.getname () +", salary="+ e.getsalary () +", hireday="+ E.gethireday ()); }}class employee{PrivateString name;Private DoubleSalaryPrivateDate Hireday; Public Employee(String N,DoubleSintYearintMonthintDay) {name = N;      Salary = s; GregorianCalendar Calendar =NewGregorianCalendar (year, month-1, day);//GregorianCalendar uses 0 for JanuaryHireday = Calendar.gettime (); } PublicStringGetName()   {returnName } Public Double getsalary()   {returnSalary } PublicDateGethireday()   {returnHireday; } Public void raisesalary(DoubleBypercent) {Doubleraise = salary * Bypercent/ -;   Salary + = raise; }}

(1) Note that there can be only one public class in a source file, but there may be any number of non-public classes where the file name must be the same as the class name of the common class.
(2) The above source file contains two classes, which we can put each class into a separate source file. At compile time, the most convenient way is to type only

Javac Employeetest.java

When the compiler discovers that Employeetest.java uses the employee class, it automatically looks for a file named Employee,class, and if it is not found, it automatically searches for Employee.java and compiles it. And if the Employee.java version is newer than the existing Employee.class version, the compiler will automatically recompile the file.
(3) A constructor contained in the employee class four methods are marked public, and any method that represents any class can call these methods.
The three instance fields of the keyword private tag indicate that only methods of the employee class themselves can access these instance domains.
Therefore, it is highly discouraged to use the public tag instance domain, which destroys encapsulation.

3.1 About constructors

From the above program can be seen
(1) The constructor has the same name as the class
(2) Each class can have more than one constructor
(3) constructors can have 0, 1, or more parameters
(3) The constructor has no return value
(4) The constructor is always called with the new operation, and the constructor cannot be invoked on an already existing object to achieve the purpose of re-setting the instance domain
(5) Note, do not define a local variable with the same name as the instance field in the constructor clock , as

   publicEmployeedoubleintintint day)   {      //Error!      //Error!      new1, day);      // GregorianCalendar uses 0 for January      hireDay = calendar.getTime();   }

The above error program in the constructor also declared the local variables name and salary, these variables can only be accessed within the constructor, thus the same name of the instance domain formed a mask, the formation of errors, note that this error is difficult to check out, pay attention!

3.2 Implicit and explicit parameters

For example, call Number.raisesalary (5), and you can see that the method Raisesalary has two parameters:
An implicit argument, the Employee class object that appears before the method name, number
An explicit parameter, which is the value in parentheses after the method name, 5
In each method, the key in this represents an implicit parameter, and, if necessary, writes the Raisesalary method in this way

   publicvoidraiseSalary(double byPercent)   {      doublethis100;      this.salary += raise;   }

This writing style can be cultivated, and the instance domain can be clearly distinguished from local variables.

3.3 Advantages of Package

The first three methods that appear in the above program are typical accessor methods, because they only return instance domain values, also known as domain accessors.
However, there are times when you need to get or set the value of an instance field, so you should provide the following three things
-A Private data field
-A public domain accessor method
-A public domain change method
This is obviously more complex than providing a simple public data field, but it also has significant advantages
(1) Can change the internal implementation, in addition to the method of the class, does not affect the other code
(2) The Change method can perform error checking, but assigning a value directly to a domain will not be processed
Note Do not write accessor methods that return references to mutable objects.

3.4 Class-based access rights

(1) A method can access the private data of the called object
(2) A method can also access private data for all objects of the owning class
Such as
Apparently called

if (Harry.equals (Boss)) ...

In method equals also accesses the private domain of Harry and boss.

3.5 Private methods

Sometimes you might want to say that a calculation code is divided into several independent helper methods that should not be part of the public interface, because they are often very close to the current implementation mechanism, or require a special protocol and a special invocation order.
At this point, just change the keyword public to private.

3.6 Final Instance Domain

When you define an instance domain using the keyword final, you must initialize such a domain when you build the object. That is, you must ensure that the value of the field is set after each constructor is executed, and that it cannot be modified in subsequent operations.
The final modifier is generally applied to the base type field, or to the domain of the immutable class. Where each method in a class does not change its object, the class is immutable.

Java Core Technology (III)--Objects and classes (1)

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.