Java Certification Course 05

zhaozj2021-02-16  122

Chapter 5 Objects and Classes

This module is the first part of the Java programming language to discuss object-oriented statements and object-oriented features.

Section 1 related issues

Discussion - The following problem is related to the materials that appear in this module:

- The element of the Java programming language that is currently learning is existing in most languages, regardless of whether they are object-oriented languages.

- What is the characteristics of Java programming language make it an object-oriented language?

- "Object-oriented" What is the true meaning of this term?

Second section

After learning this module, you can:

- Define package, polymorphism, and inheritance

- Access the modifier using private and public

- Development program segment creation and initialize an object

- Call a method for a special object

- Description constructor and method overload

- Describe the use of this reference

- Discussion Why Java application code is reusable

- In a Java program, confirm:

Package statement

- Import statement

- Class, member functions and variables

- Constructor

- Overload method

- Covering method

- Parent class constructor

Third section object foundation

Object-Oriented (OOP) statement enables the concept of the real world to become a module in a computer program. It includes features of constructors and mechanisms of tissue data and algorithms. There are three characteristics of the OOP language: package, polymorphism and inheritance. All of these features are closely related to the concept of classes.

5.3.1 Abstract data type

When the data type is composed of data items, many blocks or methods can be defined specifically on this type of data. When a program language defines a basic type such as an integer, it also defines a number of arithmetic methods (such as adding, subtraction, multiplication, and division), so it can run in this type of instance.

In many programming languages, once a collection data type has been defined, the programmer defines the application function to run on the variable of this type, which has no connection between code and collection types (unless it may be in naming rules).

Some program languages, including Java, have a close relationship between the declaration of the data type and the declaration of the code of this type variable. This connection is often referred to as an abstract data type.

5.3.2 class and objects

Abstract data type concept in the Java programming language is considered to be CLASS. The class provides definitions to the particular type of object. It specifies data inside the object, creates the features of the object, and the function running on its own data. Therefore, the class is a template. Objects is built on its class module, very similar to building a building according to architectural drawings. The same drawings can be used to build a lot of buildings, and each building is an object itself.

It should be noted that the class defines what the object is, but it is not an object. Only a copy of the class definition in the program, but there are several objects as an instance of this class. An object is instantiated using the New operator in the Java programming language.

The data type defined in the class is not very use, unless you have a destination. The method defines the operations that can be performed on the object, in other words, the method defines what is done. Therefore, all methods in the Java programming language belong to a class. Unlike C programs, Java software programs are unlikely to have methods outside of the class.

See an example of a class:

Class Empinfo {

String name;

String designation;

String department;

}

These variables (Name, Designation and Department) are called members of class Empinfo.

Instantiate an object, create it, then assign a value on its members as described below: Empinfo Employee = New Empinfo (); // Creates Instance

Employee.name = robert javaman "; // initializes

Employee.Designation = "manager"; // the Three

EMPLOYEE.DEPARTMENT = "coffee shop"; // Members

The Employee object in the Empinfo class can now be used. E.g:

System.out.println (Employee.name "IS"

Employee.Designation "AT"

EMPLOYEE.DEPARTMENT);

The print results are as follows:

Robert Javaman Is Manager At Coffee SHOP

As described below, it is now possible to put the method print () in the class to print data. Data and code can be encapsulated in a single entity, which is a basic feature of object-oriented language. The code segment named Print () can be called as a method, which is an object-oriented one-oriented statement of the term "function".

Class Empinfo {

String name;

String designation;

String department;

Void print () {

System.out.println (Name "IS" Designation "AT" Department);

}

}

Once the object is created and instantiated, the method printed the data of the class member. Implemented as follows:

Empinfo Employee = New Empinfo (); // Creates Instance

Employee.name = "Robert Javaman"; // Initializes

Employee.Designation = "manager"; // the Three

EMPLOYEE.DEPARTMENT = "coffee shop"; // Members

Employee.print (); //prints the detail

Take a look at the set data type MyDate and a function Tomorrow to assign a value for the next date.

Create a connection between myDate type and tomorrow () method as described below:

Public class mydate {

Private Int Day, Month, Year;

Public void tomorrow () {

// Code to increment day

}

}

Note - The term "private" in this statement will be described later.

The method is not (as the separated entity) runs on the data, and the data (as part of the object) operates itself.

Mydate d = new mydate ();

D. Tomorrow ();

This annotation indicates that behavior is done by an object rather than on an object. Remember, you can point to the field in the MyDate class with a point mark.

This means that "the DAY field of the MyDate object is called D. Call. So, the previous example" MyDate object's Tomorrow behavior is called by variable D. Call ", in other words, the D object is Tomorrow () operation.

The method is an object's attribute and can be used as a part of a single unit that is closely interacting with the data of its object, which is a key object-oriented concept. (If the method is different from this concept, the method is the separated entity, introduced from the outside, acts on data.) Message Passing This term is usually used to express such a concept, that is: indicating an object in its own data Do a job, an object method defines what this object can do in its own data. 5.3.3 Defining method

Definition method

Method declaration takes this format:

([]) [throws ] {}

Public void adddays (int days) {

}

The Java programming language uses a very similar approach to other languages, especially C and C , and very similar ways. Its statement uses the following format:

([]) [throws ] {}

can be any legal identifier and have certain restrictions based on the name already used.

represents the type of method return value. If the method does not return any values, it must be declared as a Void (empty). Java technology is strictly strict on the return value, for example, if a method returns an int value, then the method must return an int (only in the context waiting returns to the int value).)

Segment can carry a number of different modifiers, including public, protected, and private. The public access modifier representation can be called from any other code. Private representation can only be called by other methods in this class. Protected will be discussed in future courses.

allows the parameter value to be transferred to the method. The elements listed are separated by commas, while each element contains a type and an identifier.

Throws The clause leads to a runtime error (exception) to be reported to the call to handle it in a suitable manner. The abnormal situation is specified in .

E.g:

Public void adddays (int days) {

}

Tell the body's body, use to accept that parameters that increase the number of days to the current date. In this method, the value is referenced by the identifier DAYS.

5.3.4 value transmission

Value transfer

Java programming language only passes parameters

When an object instance is transmitted to the method as a parameter, the value of the parameter is a reference to the object.

The content of the object can be changed in the called method, but the reference to the object will never change.

The Java programming language is transmitted only by the value, that is, the parameter cannot be changed by the way to be called. When an object instance is transmitted to the method as a parameter, the value of the parameter is a reference to the object. The content of the object can be changed in the way to be called, but the object reference is never change.

The following code example can clarify this:

1 public class passtest {

2

3 float ptvalue;

4

5 // Methods to Change The Current Values6 Public Void Changeint (INT VALUE) {

7 value = 55;

8 }

9

10 Public Void Changestr (String Value) {

11 Value = New String ("DIFFERENT");

12}

13

14 Public Void ChangeObjValue (Passtest Ref) {

15 ref.ptValue = 99.0f;

16}

In one

18 public static void main (string args []) {

19

20 string Str;

21 int val;

twenty two

23 // Create An Instance of The Class

twenty four

25 passtest Pt = new passtest ();

26 // Assign THE INT

27 VAL = 11;

Twist

29 // Try to change IT

30 pt.changeint (val);

31

32 // What is the current value?

33 System.out.println ("Int Value IS: VAL);

34

35 // Assign The String

36 str = new string ("Hello");

37

38 // Try to change IT

39 pt.changestr (STR);

40

41 // What is the current value?

42 System.out.println ("Str value is:" STR);

43

44 // Now set the ptvalue

45 pt.ptvalue = 101.0f;

46

47

48 // Now change the value of the float

49 // THROUGH THE Object Reference

50 pt.changeobjvalue (pt);

51

52 // What is the current value? 53 System.out.println ("Current Ptvalue IS:"

54 pt.ptvalue);

55}

56}

This code outputs the following:

C: / student / source /> Java Passtest

Int Value IS: 11

Str value is: Hello

Current Ptvalue IS: 99.0

String objects are not changed by ChangeStr (), but the content of the PassTest object is changed.

5.3.5 THIS reference

THIS reference

Public class mydate {

Private Int Day, Month, Year;

Public void tomorrow () {

THIS.DAY = this.day 1;

// wrap arrone ...

}

}

Keyword this is used to point to the current object or class instance. Here, this.day refers to the DAY field of the current object.

Public class mydate {

Private Int Day, Month, Year;

Public void tomorrow () {

THIS.DAY = this.day 1;

// wrap arrone ...

}

}

The Java programming language automatically links all instance variables and methods to the THIS keyword, so use the keyword in some cases. The following code is equivalent to the previous code.

Public class mydate {

Private Int Day, Month, Year;

Public void tomorrow () {

Day = day 1; // no `this. 'Before` day'

// wrap arrone ...

}

}

There are also keywords this uses unusual situations. For example, a method is required to be called in some fully separated class and a reference to the current object as a parameter. E.g:

Birthday bday = new birthday (this);

5.3.6 Data Hide

Data hidden

Public class date {

Private Int Day, Month, Year;

Pubic void tomorrow () {

THIS.DAY = this.day 1;

// wrap arrone ...

}

}

Public class dateuser {

Public static void main (string args []) {

Date mydate = new mydate ();

Mydate.day = 21; // illegal!

}

}

Use the keyword private in the DAY, MONTH, and YEAR declaration of the MyDate class, enabling access to these members from any code other than the MYDATE class itself. Therefore, give a declaration to the MyDate class, the following code is illegal:

Public class dateuser {

Public static void main (string args []) {

Mydate d = new mydate ();

D.day = 21; // illegal!

}

}

Prevent direct access data variables appear surprises, but it actually has great benefits to the quality of programs that use the MyDate class. Since the individual items are unacceptable, then the only way is to read or write through the method. Therefore, if the internal consistency of the class member is required, it can be processed by the class itself. Think about the MYDATE class that allows you to freely access from the outside. The code will be very easy to do the following work:

Mydate d = new mydate ();

D.day = 32; // invalid day

D.MONTH = 2; D.day = 30; // Plausible But Wroge

D.Month = D.MONTH 1; // omit check for Wrap Round

WARNING - These and other similar assignments have led to invalid or inconsistent values ​​in the MyDate object field. This situation is impossible to expose it immediately, but will definitely terminate the program at a certain stage.

If the class data member is not exposed (in the package in the class), then the class user will be used to use the method to modify the member variable. These methods can perform validity checks. Consider the following method as a part of the MyDATE class.

Public void setday (int targetday) {

IF (targetday> this.daysinmonth ()) {

System.err.Println ("Invalid Day" TargetDay;

}

Else {

THIS.DAY = TargetDay;

}

}

Method check is to look at whether the date requested is valid. If the date is invalid, the method ignores the request and prints the information. The Java programming language will be seen later to provide a more efficient mechanism to handle the spilled method parameters. But now, you can see that the DATE class is effectively protected against the invalid date.

Note - In the above example, DaySINMOSTH () is specified as a method in the DATE class. Therefore, it has a THIS value, from this value, it can extract the answer to the required Month and Year. Since it is used with a member variable, the use of this THISINMONTH () method is redundant.

Regarding how to correctly call methods, such as "The value" of the "Month" value must be in a valid range in an effective range (or preamp and back conditions). Carefully use the front condition test to make the class easier to use again, and more reliable in reuse, because if any method is misused, the programmer using this class can discover immediately.

5.3.7 package

Encapsulate

Hidden category

Forcing users to use an interface to access data

Better maintenance

In addition to the data of the protective objects are not modified, in the case of ensuring that the required side effects are properly processed, forcing the user to access the data through the method to make the reuse of the class easier. For example, under the MYDATE class, consider how to construct a tomorrow () method.

If the data is fully accessible, each user of the class needs to increase the value of the DAY, test the number of days of the current month, and handle the month-end (and may be year-end). This is meaningless and is easily erroneous. Only these requirements are very well understood to date, and other data types may have a small known similar limit. By forcing the user to use the Tomorrow () method to ensure that each person can continuously and correctly handle the necessary side effects.

Data hidden usually refers to packaging. It distinguishes the external interface of the class with the implementation of the class and hides the implementation details. Forcing the user to use the external interface, even if the details change, it can also be used to assume its functionality to ensure that the code calls it continues. This makes the code maintenance easier.

Section 4 Reserved Method Name

Overload method name

It can be used as follows:

Public void Println (INT i)

Public void println (Float F)

Public void println ()

Parameter table must be different

Return type can be different

In some cases, it may be necessary to write several methods of doing the same work but with different parameters in the same class. Consider a simple method, it tries to output the text representation of parameters. This method is called PrintLn ().

Now suppose printing each int, float, string type requires a different printing method. This is reasonable because various data types require different formats, and may require different processing. Three methods can be created separately, namely: printint (), printfloat (), and printstring (). But this is very boring.

Java is the same as other programming languages, allowing for more than one method to reuse method names. It is clear that it can work only when something can distinguish it actually needs. In the case of three printing methods, this may be distinguished based on the number and type of parameters.

By reuse method names, the following methods can be ended:

Public void Println (INT i)

Public void println (Float F)

Public void println ()

When writing code to call one of these methods, select a suitable method according to the type of parameters provided.

There are two rules suitable for overloading methods:

The parameter table of calling statements must have sufficient, so that the correct method is allowed to be called. Normal expansion promotion (eg, single-precision type FLOAT to double precision type Double) may be applied, but this will result in confusion under certain conditions.

The return type of the method can vary, but it is not enough to make the return type into a unique difference. The parameter table of the overload method must be different.

Section 5 construction and initialize the object

Construct and initialize the object

Calling new xxx () to allocate space for the new object, the following results:

The space of the new object is assigned and initialized to 0 or null value

Explicit initialization

Constructor is executed

It has been seen that in order to assign space to the new object, how to be called to NEW XXX (). Sometimes it will see that the parameters are placed in parentheses, such as: New Button ("PRESS ME"). Use the keyword NEW can cause the following:

First, the spatial space of the new object is assigned and initialized to 0 or null. In the Java programming language, this phase is unidiable to ensure that there is no size of the random value during the allocation space.

Next, explicit initialization is performed.

Third, the constructor is executed, it is a special method. Parameters transmitted to new brackets are passed to the constructor.

This section discusses this last two steps.

5.5.1 Explicit Member Initialization

Explicit member initialization

Public class initialized {

Private int x = 5;

Private string name = "fred";

Private date created = new date ();

//Methods Go Here

...

}

If a simple assignment expression is placed in a member declaration, explicit members are initialized during the object construct.

Public class initialized {

Private int x = 5;

Private string name = "fred";

Private date created = new date ();

//Methods Go Here

...

}

5.5.2 Constructor

Constructor

Method name must match the class name

For methods, don't declare return type

The explicit initialization mechanism just described has provided a simple approach to the initial value of the setting field in an object. However, sometimes a method is required to perform initialization. Perhaps it is also necessary to handle possible errors. Or want to initialize with a cycle or conditional expression. Or want to pass the parameters to the construction process in order to require the code that constructs a new object can control the object it created. The final step of initialization of a new object is to call a method called constructor.

The constructor is confirmed by the following two rules:

The method name must be fully matched with the class name.

For methods, don't declare return type

Constructor

Public class xyz {

// Member Variables Go There

Public xyz () {

// set up the object.

}

Public xyz (int x) {

// set up the object with a parameter

}

}

Public class xyz {

// Member Variables

Public xyz () {// no-arg constructor

// set up the object.

}

Public XYZ (INT X) {// int-arg constructor

// set up the object using the parameter x.

}

}

Note - Since the method is used, the constructor can be overloaded by providing a different parameter table for several constructor. When issuing new xyz (argument_list), the parameter table passed to the New statement is determined which constructor is adopted.

5.5.3 Call the overloaded constructor

Call overload constructor

PUBLIC CLASS EMPLOYEEEE {

PRIVATE STRING NAME;

Private int sale;

Public Employee (String n, int S) {

Name = n;

Salary = S;

}

Public Employee (String n) {

THIS (N, 0);

}

Public Employee () {

THIS ("Unknown");

}

}

If there is a class with several constructor, then you will want to copy a certain aspect of the constructor to another constructor. This is achieved by using keyword this as a method call to achieve this.

PUBLIC CLASS EMPLOYEEEE {

PRIVATE STRING NAME;

Private int sale;

Public Employee (String n, int S) {

Name = n;

Salary = S;

}

Public Employee (String n) {

THIS (N, 0);

}

Public Employee () {

THIS ("Unknown");

}

}

In the second constructor, there is a string parameter, calling this (n, 0) to pass control to another version of the constructor, ie, a string parameter and a constructor of an int parameter.

In the third constructor, it does not have a parameter, calling this ("unknownn") transfer control to another version of the constructor, ie, using a String parameter constructor.

Note - For any call to this, if it appears, in any constructor must be the first statement.

5.5.4 Default constructor

Default constructor

Every class has

Create an object instance with new xxx ()

If you add a constructor declaration with parameters, it will make the default invalid.

Each class has at least one constructor. If you do not write a constructor, the Java programming language will provide one. This constructor has no parameters, and the function body is empty.

The default constructor can create an object instance with new xxx (), which will be required to provide a constructor for each class. Note - If you add a constructor with parameters declare in a class, the class has not been explicitly constructed before, then the default constructor will be lost. Based on this, the call to new xxx () will cause compilation errors. It is important to realize this.

Section 6

5.6.1 IS A relationship

IS A relationship

EMPLOYEE class

PUBLIC CLASS EMPLOYEEEE {

String name;

Date HiRedate;

Date DateOfbirth;

}

In programming, you often create a model of something (such as a staff member) and then require a more specialized version of the basic model. For example, a manager may need a manager. Obviously manager is actually a staff member, just a staff with additional characteristics.

Take a look at the examples of the following examples:

PUBLIC CLASS EMPLOYEEEE {

String name;

Date HiRedate;

Date DateOfbirth;

String jobtitle;

Int grade;

...

}

This example describes data replication between Manager and Employee classes. In addition, there may be many methods suitable for both Employee and Manager. Therefore, there is a need to create a new class from an existing class. This is called a subclass.

5.6.2 Extends Keywords

Extends keyword

PUBLIC CLASS EMPLOYEEEE {

String name;

Date HiRedate;

Date DateOfbirth;

String jobtitle;

Int grade;

...

}

Public class manager extends Employee {

String department;

Employee [] Subordinates;

}

In object-oriented languages, special mechanisms are provided, allowing programmers to define a class with a previously defined class. As shown below, you can use the keyword Extends to implement:

PUBLIC CLASS EMPLOYEEEE {

String name;

Date HiRedate;

Date DateOfbirth;

String jobtitle;

Int grade;

...

}

Public class manager extends Employee {

String department;

Employee [] Subordinates;

...

}

In such an arrangement, the Manager class is defined and has all variables and methods owned by Employee. All of these variables and methods are inherited from the definition of the parent class. All programmers need to do is to define additional features or regulations will apply.

Note - This method is a great progress in maintenance and reliability. If you modify in the Employee class, the Manager class will automatically modify without requiring programmers to do anything, except for it.

Note - The description of a inheritance method or variable exists only in the API document that is defined for the member. When browsing to explore a (child) class, you must check the inheritance members in the parent class and other ancestors.

5.6.3 Parameters and heterogeneous collection

Parameters and heterogeneous collection

Collection of classes with common sites are called similar collections, such as arrays

Collection with different objects is aligned, such as collections of classes inherited from various other classes

You can create a collection of objects with common classes (such as arrays). This collection is called similar collections.

The Java programming language has an object class, so due to the polymorphism, it can collect all kinds of elements, just as all classes expand the class object. This collection is called heterogeneous collection. Create a Manager and cautiously, it seems unrealistic to assign it to the variable of type EMPLOYEE. But this is possible, and there are many reasons why this effect is achieved.

With this method, a method of accepting a general-purpose object can be written. In this case, it is class EMPLOYEE, and is properly operated on the objects of any subclass of it. A method can then be generated in the application class, the application class draws a staff, and compares its salary to a threshold to determine the tax responsibility of the staff. Using polymorphism, you can do this:

// in The Employee Class

Public Taxrate FindTaxrate (EMPLOYEE E) {

// Do Calculation and return a Tax Rate for e

}

// MeanWhile, Elsewhere in the application class

Manager m = new manager ();

:

Taxrate t = findtaxrate (m);

This is legal, because a manager is a staff member.

Alien collection is the collection of things that is not similar. In object-oriented languages, you can create a collection of things. All have a common ancestor-Object class. Such as:

Employee [] staff = new employee [1024];

Staff [0] = new manager ();

Staff [1] = new Employee ();

It can even write a sorting method that sorts the staff by age or salary, and Ignore some of them may be a manager.

Note - Each class is a subclass of Object, so it can be used as a container of any object with an Object array. The only thing that cannot be added to the Object array is the basic variable (and the packaging class, will be discussed in the module 6, please note this). Better than the Object array is vector class, which is designed to store the same class to collect objects.

5.6.4 Singher Inheritance

Single inheritance

When a class is inherited from a unique class, it is called a single inheritance. Single inheritance makes the code more reliable. The interface provides more inheritance, and there is no (more inherited) shortcomings.

The Java programming language allows a class that can only be extended into one other class. This limit is called a single inheritance. The advantage of single inheritance and multi-inheritance is the topic of the broad discussion between object programmers. The Java programming language enhances single inheritance restrictions to make the code more reliable, although this sometimes adds programmers' work. Module 6 discusses a language feature called interface (Interface), which allows most benefits of multiple inheritance, not affected by its disadvantages.

An example of a subclass with inheritance is shown in Figure 5-1:

Figure 5-1 inheritance

5.6.5 Constructuring Function cannot be inherited

Constructor cannot be inherited

Subclasses inherit all methods and variables from superclass (parent class)

Subclass does not inherit constructive function from superclass

Two methods that contain constructors are

Use the default constructor

Write one or more explicit constructor

Although a sub-class inherits all methods and variables from the parent class, it does not inherit the constructor, and master this is important.

A class can get a constructor, only two ways. Or write the constructor, or there is no write constructor at all, the class has a default constructor.

Note - The parent class constructor is always accessed in addition to the sub-structural function. This will discuss in detail in the back modules.

5.6.6 polymorphism

Polymorphism

Ability has many different formats, just called polymorphism. For example, managers can access staff methods.

An object has only one format a variable has many formats, which can point to objects in different formats.

Describe the manager as a employee is not just a simplicity of the relationship between these two classes. Recall that the manager has all the properties, members, and methods of the parent class staff. That is to say, any legal operation on Employee is also legal on Manager. If Employee has two methods, both methods, then the Manager class is also available.

A object has only one format (it is in the configuration). However, since variables can point to objects in different formats, the variable is polymorphism. In the Java programming language, there is a class that is the parent class of all other classes. This is the java.lang.Object class. Therefore, in fact, the previous definition is simply:

Public Class Employee Extends Object and

Public Class Manager Extends Employee

The Object class defines many useful methods, including toString (), which is why each of the Java software can convert to a string representation. (Even though this only has limited uses).

Like most object-oriented languages, Java actually allows you to reference an object with a variable, which is one of the parent class type. Therefore, it can be said:

Employee E = New Manager ()

Use the variable E because the object part you can access is only part of Employee; the special part of Manager is hidden. This is because the compiler should realize that E is an EMPLOYEE instead of a Manager. Thus, the following is not allowed:

e.Department = "finance"; // illegal

Note - Polymorphism is a runtime issue, opposite the overload, the overload is a compile time.

5.6.7 Keyword Super

Keyword Super

Super is used in the class to reference its superclass.

Super class is used to call the superclass.

The super-class behavior is called, as if the object is a super class component.

Calling behavior does not have to happen in the superclass, it can automatically trace the top class.

Keyword SUPER can be used to reference superclars in this class. It is used to reference the super class member variable or method.

Usually when a method is covered, the actual purpose is not to replace the existing behavior, but to extends to some extent.

Use Keyword Super to get:

PUBLIC CLASS EMPLOYEEEE {

PRIVATE STRING NAME;

Private int sale;

Public string getDetails () {

Return Name: " Name " / NSALARY: " SALARY;

}

}

Public class manager extends Employee {

PRIVATE STRING Department DEPARTMENT;

Public string getDetails () {

Return super.getdetails () // Call PARENTS '

//Method

"/ NDEPARTMENT:" Department;

}

}

Note that the success of the super.method () format, if the object already has a parent class type, then its method's entire behavior will be called, including all its secondary effects. This method does not have to be defined in the parent class. It can also be inherited from some ancestors.

5.6.8 InstanceOf operator

InstanceOf operator

Public Class Employee Extends ObjectPublic Class Manager Extends Employee

Public Class Contractor Extends EMPLOYEE

Public void method (employee e) {

IF (E InstanceOf Manager) {

// Get Benefits and Options Along with Salry

} Else if (e instanceof contractor) {

// Get Hourly Rates

} else {

// Temporary Employee

}

}

If you can use the reference to pass the object to their parent class, sometimes you want to know what you do, this is the purpose of the InstanceOf operator. Suppose the class level is expanded, then you can get:

Public Class Employee Extends Object

Public Class Manager Extends Employee

Public Class Contractor Extends EMPLOYEE

Note - Remember, when acceptable, Extends Object is actually redundant. Here it is only a prompt item.

If an object is accepted by a reference to the EMPLOYEE type, it does not become a Manager or Contractor. Can be tested in instanceof in this way:

Public void method (employee e) {

IF (E InstanceOf Manager) {

// Get Benefits and Options Along with Salry

} Else if (e instanceof contractor) {

// Get Hourly Rates

} else {

// Regular Employee

}

}

Note - In C , you can use RTTI (runtime type information) to do a similar thing, but in the Java programming language is more powerful.

5.6.9 Type Conversion of Objects

Object type conversion

Use instanceof to test the type of object.

Use type conversion to restore all the features of an object.

Check the correctness of the type conversion by the following prompt:

The upward type conversion is implicitly implemented.

The down type conversion must be for subclasses and checked by the compiler.

When the runtime error occurs, the reference type is checked at runtime.

When you receive a reference to the parent class, you can determine that the object is actually what you want by using the InstanceOf operator, and can convert the reference to the entire function of the object.

Public void method (employee e) {

IF (E InstanceOf Manager) {

Manager m = (manager) e;

System.out.println ("this is the manager of" m.department);

}

// REST OF OPERATION

}

If you don't have to force type conversion, the attempt to reference e.Department will fail because the compiler cannot locate members of the DEPARTMENT in the Employee class.

If you don't have a test of instanceof, there will be a risk of failure. Typically, the type of attempt to convert an object is to pass several inspections:

The upward mandatory type conversion class level is always allowed, and in fact no forced type conversion operator is required. It can be implemented by a simple assignment.

For the down type conversion, the compiler must meet the type conversion at least possible such conditions. For example, an attempt to convert the Manager reference type to Contractor is certainly not allowed because Contractor is not a Manager. Classes that are incident in types must be a subclass of current reference types. If the compiler allows the type conversion, the reference type is checked at runtime. For example, if InstanceOf checks from the source program, the object that is converted is actually not the type that it should be converted into in, then a runtime error occurs. An exception is a form of runtime error and is the topic in the back module.

Section 7 coverage method

Coverage method

Subclasses can modify the behavior from the parent class inheritance

Subcaries can create a method of different functions with the parent class, but have the same

name

Return type

Parameters Table

In addition to the additional additional characteristics, a new class can also be generated on the old class, it can also modify the current behavior of the parent class.

If a method is defined in the new class, its name, the return type, and the parameter table just matches the name, return type, and parameters of the middle of the parent class, then the new method is called the overlay method.

Note - Remember that the method of having the same name in the same name is simple overlay. This causes the compiler to determine which method of the call is used.

Consider these methods in the Employee and Manager classes:

PUBLIC CLASS EMPLOYEEEE {

String name;

Int Salry;

Public string getDetails () {

Return "Name:" Name "/ N"

"SALARY:" SALARY;

}

}

Public class manager extends Employee {

String department;

Public string getDetails () {

Return "Name:" Name "/ N"

"Manager of" department;

}

}

The Manager class has a defined getDetails () method because it is inherited from the Employee class. The basic method is replaced by the subclass of the version of the subclass.

Coverage method

Virtual method call

Employee E = New Manager ();

e.getdetails ();

Compile time type and runtime type

Suppose the examples and the following scenarios on page 121 are correct:

Employee E = New Employee ();

Manager m = new manager ();

If you request E.GETDETAILS () and M.GetDetails, different behaviors will be called. The Employee object will perform the getDetails version related to Employee, and the Manager object will execute the getDetails () version related to Manager.

Not obvious is as follows:

Employee E = New Manager ();

e.getdetails ();

Or some similar effects, such as a general method parameter or an item from a different set.

In fact, you get behaviors related to the runtime type of the variable (ie, the type of variable), rather than behavior related to the compile time of the variable. This is an important feature of object-oriented language. It is also a feature of polymorphism, and is often called a virtual method call.

In the precedent, the E.GETDETAILS () method being executed is from the real type of the object, Manager.

Note - If you are a C programmer, you will have an important difference between Java programming languages ​​and C . In C , you want to get this behavior, you can only mark the method into Virtual in the source program. However, this is not normal in the pure face to the object language. Of course, C does this to improve the execution speed. Section 8 call overlay method

Rule of overlay method

There must be one return type as the method it covers it.

Can't access the difference than it covered

More exceptions cannot be thrown more than what it covers.

Rule of overlay method

Remember, the name of the sub-method and the order of sub-method parameters must be the same as the name of the method in the parent class, and the order of the parameters so that the method overrides the parent class version. The following rules apply to coverage methods:

The return type of the coverage method must be the same as the method it covers.

Covering method cannot be more accessibility than the method it covers

The coverage method cannot throw more abnormalities than the methods it covers. (Exceptions will be discussed in the next module.)

These rules originate from the properties of polymorphisms and Java programming languages ​​must ensure that "type security" needs. Consider this invalid program:

Public class pent {

Public void method () {

}

}

Public class child extends pent {

Private void method () {

}

}

Public class useboth {

Public void othermethod () {

PARENT P1 = New Parent ();

PARENT P2 = New Child ();

p1.method ();

p2.method ();

}

}

Java programming language semantics, p2.method () causes the method's Child version to be executed, but because the method is declared as Private, P2 (declared as a parent) cannot access it. Thus, language semantics conflicts.

Section 9 calls the parent class constructor

Call the parent class constructor

The initialization of the object is very structured.

When an object is initialized, the following behavior occurs in order:

Storage space is assigned and initialized to 0 values

Each class in the level is explicitly initialized

Each class in the hierarchy is called constructor

In the Java programming language, the initialization of the object is very structured. This is to ensure safety. In the previous module, I saw what happened when a particular object was created. Due to the inheritance, the image is completed, and the following behavior occurs in order:

Storage space is assigned and initialized to 0 values

Explicit initialization

Call constructor

Each class in the hierarchy will occur in the last two steps, starting from the uppermost layer.

Java technology security mode requires that all aspects of the object of the parent class must be initialized before the subclass performs anything. Therefore, the Java programming language always calls the version of the parent class constructor before executing the sub-constructor.

Call the parent class constructor

In many cases, the parent class object is initialized using the default constructor.

PUBLIC CLASS EMPLOYEEEE {

String name;

Public Employee (String n) {

Name = n;

}

}

Public class manager extends Employee {

String department;

Public Manager (String S, String D) {

Super (s);

Department = D;

}

}

Whether it is super or this, it must be placed in the first line of constructor.

Call the parent class constructor

Typically define a constructor with parameters, and use these parameters to control the structure of the parent class part of an object. A special parent class constructor may be called a part of the initialization of subclass by calling keyword SUPERs from the first line of the subclass constructor. To control the call of the specific constructor, you must provide SUPER () to provide the appropriate parameters. When the SUPER with parameters is not called, the default parent class constructor (ie, the constructor with 0 parameters) is implicitly called. In this case, if there is no default parent class constructor, it will cause compilation errors. PUBLIC CLASS EMPLOYEEEE {

String name;

Public Employee (String n) {

Name = n;

}

}

Public class manager extends Employee {

String department;

Public Manager (String S, String D) {

Super (s); // Call Parent Constructionor

// with string argument

Department = D;

}

}

Note - Call SUPER () can assign any number of suitable parameters to different constructors in the parent class, but it must be the first statement in the constructor.

When used, Super or THIS must be placed in the first line of the constructor. Obviously, both cannot be placed in a single line, but this is in fact is not a problem. If you write a constructor, it has neither called Super (...) and calls this (...), and the compiler is automatically inserted into a call to the parent class constructor without parameters. Other constructors can also call super (...) or this (...), call a Static method and the data chain of constructor. Finally, the parent class constructor (possibly several) will execute before any subclass constructor in the chain.

Section 10 group

5.10.1 package

package

The package statement must be declared in the beginning of the source file file.

According to the source program file, only one package declaration is allowed

// Class Employee of The Finance Department for Thae

// ABC COMPANY

Package abc.financedept;

PUBLIC CLASS EMPLOYEEEE {

...

}

The name of the package is hierarchical, separated by a circle

The Java programming language provides a Package mechanism as a way to group related classes. To date, all of these examples belong to the default or unambiguous package.

You can use a package statement to indicate a special package in the source program file.

// Class Employee of The Finance Department for Thae

// ABC COMPANY

Package abc.financedept;

PUBLIC CLASS EMPLOYEEEE {

...

}

Package declaration, if any, must be at the beginning of the source program file. It can be started with blank and annotations without other means. Only one package declaration is allowed to control the entire source file.

The package name is hierarchical, separated by a dot. Typically, the elements of the package name are smaller throughout. However, class names are usually starting at a capital letter, and the first letter of each additional word can be capitalized in a zone classification name.

5.10.2 IMPORT statement

IMPORT statement

Tell the compiler where to find a class to use, you must first declare all classes

Import abc.financedept. *;

Public class manager extends Employee {

String department;

Employee [] Subordinates;

}

When you need to use a package, use the Import statement to tell the compiler to find the class. In fact, the package name is part of the name of the class in the package (such as ABC.FINAnceDept). You can reference the Employee class as abc.financedept.employee, or you can use the import statement and use only class name EMPLOYEE. Import abc.financedept. *;

Public class manager extends Employee {

String department;

Employee [] Subordinates;

}

Note The -import statement must be preceded to all classes.

When using a packet declaration, it is not necessary to introduce the same package or any element of the package. Remember, the Import statement is used to bring classes in other packages to the current name space. The current package, whether explicitly or implied, is always part of the current name space.

5.10.3 Directory layout and ClassPath environment variables

Directory layout and ClassPath environment variables

The package is stored in a directory tree containing the package name.

Package abc.financedept

PUBLIC CLASS EMPLOYEEEE {

}

Javac -d. Employee.java

What is the directory path of Employee.class?

The package is stored in a directory tree containing a branch of the package. For example, the EMPLOYEE.CLASS file from the previous page must exist in the following directory:

Path / ABC / FinanceDept

The root directory of the catalog tree of the package of the book file is in the ClassPath.

The -d option of the compiler specifies the root of the package, and the class file is placed in it (the PATH shown above).

The Java Technical Compiler creates a package directory and moves the compiled class file to it when using the -d option.

C: /jdk1.2/source/> javac -d. Employee.java

Create a directory structure ABC / FINANCEPT in the current directory (".").

The ClassPath variable has not been used before because it is not set, then the default behavior of the tool will automatically include the standard location of the class distribution and the current work directory. If you want to access the package located elsewhere, you must set the classpath variable to explicitly override the default behavior.

C: /jdk1.2/source/> javac -d c: / mypackages Employee.java

In order to make the compiler to the manager.java file in the compile pre-page page, the ClassPath environment variable must include the following packet path:

Classpath = C: / mypackages ;.

Exercise: Use objects and classes

Practice Purpose - Write, compile and run three programs, by mimicing the use of bank accounts, constructor and data hiding, etc. Object-oriented concepts.

First, ready

In order to successfully complete the experiment, the concept of classes and objects must be understood.

Second, the task

First class experiment: bank account

1. Create a class, Account.java, which defines the bank account. Decide what kind of account should be done, what kind of data should be stored, and what kind of method will be used.

2. Use a package, bank, to include the class

Secondary experiment: Account type

1. Modify the primary experiment, and thus the Accounts are divided by the details of the CheckingAccount class.

2. Allow checks to provide overflow protection.

Level 3 Experiment: Online Account Service

1. Create a simple application, Teller.java, which uses a level 1 or secondary experiment to provide an online account account opening service. Third, practice summary

Discuss - spend a few minutes to discuss the experience, problems or discovery of experimental exercises.

- Experience explanation summary application

Fourth, check the progress

Check it before proceeding to the next module, confident that you can:

- Define package, polymorphism and inheritance

- Use access modifiers private and public

- Develop a block to create and initialize an object

- Modeling method on a particular object

- Describe constructor and method overload

- Describe what role from this reference

- Discuss why Java application code is reusable

In the Java software program, confirm:

Package statement

- Import statement

- class member function and variable

- Constructor

- Overload method

- Covering method

- Parent class constructor

V. Thinking

Since you understand objects and classes, how do you use this information in current or future work?

转载请注明原文地址:https://www.9cbs.com/read-8105.html

New Post(0)