Object-oriented language base 2 (1)

zhaozj2021-02-11  206

Object-oriented language base 2 (1)

Summary:

Jeff Friesen explores the fields and methods in his second part of the object-oriented language base series. In this article, you will understand how field, parameters, local variables, and how to define and access fields and methods.

Nounted words, prompts and notices, homework, and other information on this column, see related "learning guidelines". (6400 words)

As the saying goes: a leaflet, do not see the forest. This sentence refers to the overall detailed understanding of the overall understanding. So when you introduce the Java class and object, what else is more confused than too thin research fields and methods? That's why in the first part of this series, I will introduce the overall: class and object, and the reason for the introduction of the fields and methods. However, as you can eventually enter the forest and put your attention on the tree, this month's column will tell the fields and methods very detailed.

Object-Oriented Language Basic Series:

One: How to define classes and create objects

2: Declaration, access field and method

Three: Structure: Build objects from other objects

4: Inheritance: Building a layer building

Five: base class

Six: Use interfaces to achieve more secure multiple inheritance

7: Learn more features of Java and adjust the framework in your class architecture

Java variables can be divided into three categories: fields, parameters, and local variables. I will introduce the field first, introduce the parameters and local variables when discussing the method later.

Define field

The field is defined in the variable in the class, which is used to save the status of an object (instance field) or class status (class field). Use the following Java syntax to define a variable:

('PUBLIC' | 'Private' | 'Protected')]]]

"Final '| volatile']]]]

['Static'] ['Transient']

DATA_TYPE FIELD_NAME ['=' Expression] ';'

The definition of a field specifies the name of the field, the data type, the expression (initialized field value), access limits, and modify the identity. Select a data type and name that is not a reserved word as a field, for example:

Class Employee

{

String name; // employee name

Double Salry; // Salary

INT jobid; // Working surface (such as accounting, attendance, manager, etc.)

}

The Employee class defines three fields: Name, Salary, and JobID. When a Employee object is created, Name finally keeps a reference to a String object to save the name of the employee. The Salary field will save the employee's salary, while JobID saves a plastic variable to identify employee's work.

Access qualifier

You can define a field: public, private, or protected by arbitrarily using the following three access limiting keywords: public, private or protected. Acquisition qualifiers determine the code of the code in other classes to the access rights of this field. Access range From full access to completely ineffective.

If you do not use access qualifiers when defining variables, Java will assign this field a default access level, from all classes in the class to the same package, all classes in the same package. (Imagine the package into a class library - I will tell this concept in the later article.) Any class that is not defined in the same package cannot access the field, for example::

Class myclass

{

INT FRED;

}

Only the MyClass class and the code defined in other classes in myclass packs can access FRED.

If you define a field as Private, only the code in his own class can access this field. Any other class, no matter which package, you cannot access this field. Class Employee

{

PRIVATE DOUBLE SALY;

}

Only the EMPLOYEE class can access Salary;

If you define a field as public, not only the code in his own class, and the classes in all other packages can also access this field, such as:

Public Class Employee

{

Public String Name;

}

The code in the Employee class and the code in all other packages can access Name (Employee must be defined as public to enable categories in other packages).

Define all fields as PUBLIC will violate data package principles. Imagine that you have created a Body class to imitate people's body, Eye, Heart, and Lung categories to imitate their eyes, hearts and lungs. The reference fields such as Eye, Heart, and Lung, etc. are defined in the Body class, as in the following example:

Public Class Body

{

Public eye lefteye, righteye;

Private heart health;

Private Lung Leftlung, Rightlung;

}

The LefTeye and RightEye fields are declared as public because people's eyes are visible to the observer. However, Heart, Leftlung and Rightlung are declared for Private because these organs are hidden in the human body. Imagine if Heart, Leftlung and Rightlung are declared as public, a body exposed to the heart and lungs can still work as before?

Finally, a field is defined as protected to be similar to the default access level. The only difference between the two is a subclass of such classes to access the protected field. E.g:

Public Class Employee

{

Protected string name;

}

Only the code in the Employee class and all other classes in the Employee package, as well as subclats of the Employee class (defined in any package) to access NAME.

Modify logo

You can use the following modification to qualify keywords to define a field: Final or Volatile and / or Static and / or Transient.

If you define a field as Final, the compiler will ensure that the field is used as a constant-read-only variable to initialize and process. Because the compiler knows that constant is constant, internal optimization is performed in the bytecode of the program. Such examples:

Class Employee

{

Final int accessant = 1;

Final Int Payroll_Clerk = 2;

Final Int Manager = 3;

Int jobiD = accountant;

}

Three final INT fields are defined in the above example: Accountant, Payroll_Clerk and Manager.

Note: Hands all characters and use underscores in a constant statement. This will help to distinguish constants and write-on variables at the time of analysis of source code.

If you declare a field as Volatile, multi-thread will be able to access this field, while the specific compiler will prevent optimization to enable this field to be properly accessed. (You will learn the volatile field for discussion threads in the columns.)

If you define a field as Static, all objects will share a copy of this field. When you assign a new value to this field, all objects will get this new value. If not specified as static, this field will be an instance field, each object uses their own copy. Finally, defined field values ​​will not be saved during the object serialization process. (I will study this topic in the column later.)

Instance field

"Instance Field" is the field that does not use the Static modified identifier defined. The instance fields and objects are closely connected - instead of classes. When modified in an object code, only this related class instance - object - can get this change. The instance field is created with the creation of objects, released with the release of objects.

The next example demonstrates an instance field:

Class SomeClass1

{

INT i = 5;

Void print ()

{

System.out.println (i);

}

Public static void main (string [] args)

{

Someclass1 sc1 = new someclass1 ();

System.out.println (sc1.i);

}

}

SomeClass1 defines an instance field named I, and demonstrates two methods for accessing the instance field in the same way. Method. Both methods and instances are in the same class.

Access the instance field through an instance method in the same class, you only need to use this field name. When the instance method in other classes accesses the instance field, you must have a reference variable for an object of the instance field you want to access, which stores the address of the object created from the class. The reference variable of this object - and the point operator - be used as the prefix of this instance field name. (Example Method You can see later this article.)

Access the instance field through a class method in the same class, create an object from this class, assign it to a reference variable and make this variable as the prefix of this instance field. The steps of accessing this field in the same category are accessed by the class method of other classes. (This article is later explained later.)

When the JVM creates an object, the memory space is allocated to each instance field and clear the memory of these fields. To assign a default value to the instance field. The default value depends on its data type. The default value of the reference field is NULL, the digital field is 0 or 0.0, the Boolean value is false, the character is / u0000.

Class field

The class field is a field defined with static keywords. Class fields and class contacts - not objects. This class (and all created objects) can be perceived when modified in a class code. Class fields are created with classes, released with class uninstallation. (I believe that some JVM uninstall the class and other JVMs are not.)

The following example illustrates the class field:

Class SomeClass2

{

Static int i = 5;

Void print ()

{

System.out.println (i);

}

Public static void main (string [] args)

{

System.out.println (i);

}

}

SomeClass2 defines a class field named I, and demonstrates two methods - instance methods and class methods to access the I in the same way (two methods and class fields in the same class).

Access the class field through an example method in the same kind, you only need the name of this class field. Other classes of instance methods access to this class field to define the class name of this class field as the prefix of the class field. For example: using someClass2.i to enable other classes to access I-these classes must be in the SomeClass2 package, because someClass2 is not declared as public.

When you type in the same class, you only need to use this field name. Other class methods are accessible when accessing this class field, and the instance method in other classes accesses the class field process is the same. When class is loaded, the JVM assigns memory to each class field and assigns the class field to default. The default value of the class field and the default value of the instance field.

In the Java field, the field is a global variable. Such examples:

Class global {

STATIC STRING NAME;

}

Class Useglobal

{

Public static void main (string [] args)

{

Global.name = "useglobal";

System.out.println (global.name);

}

}

The above code defines two classes in the same file: Global and Useglobal. If you compile and run this program, the JVM loads Useglobal and starts to execute the principal code code of the main (). JVM looks up, loads, and checks the Global class when you find global.name. When the Global class is checked, the JVM assigns memory to Name and initializes it to NULL. In the background, JVM creates a String object and initializes the characters in dual quotes - IGLOBAL. And give this reference to Name. Then, the program acquires the reference to the String object pointing to Global.Name, then pass this to System.out.println (). Finally, the content of the String object will be displayed on the standard output device.

Because both Global or Useglobal is clearly defined as public, you can choose any name as the name of the source file. The result of compiling this file is two class files: global.class and useglobal.class. Because there is a Main () method in UseGlobal, this program is run with this class. Type: Java Useglobal to run this program in the command line.

If you type: Java Global, you will get the following error:

Exception in thread "main" java.lang.nosuchmethoderror: main

The last word of the error message MAIN indicates that the Java compiler did not find the main () method in the class Global.

constant

"Constant" is a read-only variable; the value of the variable cannot be changed when the JVM initializes this variable.

Use the final key to define a constant. There are two fields - instances and class fields, constants have two - instance constants and types of orders. In order to improve efficiency, you should create a class constant, or a final static field. Such as:

Class Constants

{

Final Int first = 1;

Final static int special = 2;

Public static void main (string [] args)

{

INT ITERATION = Second;

IF (Iteration == First) // Compiling errors

System.out.println ("First Iteration");

Else

IF (Iteration == SECOND)

System.out.println ("SECOND ITERATION");

}

}

The Constants class in the above example defines a pair of constants --First and Second. First is an instance constant because JVM assigns a copy of a first for each constants object. Conversely, because JVM only creates a second copy after loading the Constants class, SECOND is a class constant.

Note: When you try to access the first flight directly, you will cause a compilation error. The constant first until an object is created, so First can only be accessed by this object - not class. Use constants in the following cases:

1. In the source code, modify the initial value of the constant is easier and less error compared to replace all the numbers.

2. Constants can make the source code more readable and easier to understand. For example: constant Num_Array_Elements is more meaningful than the number 12.

Enumerated type

Imagine you writing a Java program, zoo1, to imitate the animals of a group of circus:

Listing 1, Zoo1.java

//Zoo1.java

Class Circusanimal

{

Final static int Tiger = 1;

Final static int lion = 2;

FINAL Static Int Elephant = 3;

Final static int monkey = 4;

}

Class zoo1

{

PRIVATE INT ANIMAL;

Public static void main (string [] args)

{

ZOO1 z1 = new zoo1 ();

Z1.animal = circusanimal.tiger;

// later .........

IF (z1.animal == CircusanImal.teger)

System.out.println ("This Circus Animal IS A Tiger!");

Else

IF (z1.animal == circusanimal.monkey)

System.out.Println ("this circus animal is a monkey!");

Else

System.out.Println ("Don't know!";

}

}

Zoo1.java defines two classes: Circusanimal and ZOO1, class Circusanimal defines some convenient integration constants to distinguish between different animals. Zoo1 is a static class - his main () method runs zoo1 program.

The main () method creates a ZOO1 object that assigns the reference to Z1 and initializes the AnImal instance field of this object to Circusanimal.tiger. Although Animal is private, but the main () method is also able to access those variables - references to this object - because main () is part of the class defining the class of animal. Next, Main () checks the current value of Animal and outputs an appropriate message according to the output.

Zoo1 has a special problem: Animal's int data type keyword. Suppose we assign 987324 to z1.animal - that is legal because Animal and 987324 are integrity. But the result of this assignment is meaningless. What is the animal 987324? Putting integer as animal data type may generate some unreasonable code, which is often easily generated by BUGS. The solution to this problem is to give an iMal a very appropriate data type and can limit the range of values ​​assigned to animal. This is the basic principle of using enumeration data types.

The enumeration data type is a reference data type for a set of restrictions. Each value is an object created by the enumeration data type, as follows:

Listing 2: Zoo2.java

//Zoo2.java

Class Circusanimal

{

Static Final Circusanimal Tiger = New Circusanimal ("Tiger");

Static Final Circusanimal Lion = New Circusanimal ("Lion"); Static Final Circusanimal ELEPHANT = New Circusanimal ("Elephant");

Static Final Circusanimal Monkey = New Circusanimal ("Monkey");

PRIVATE STRING ANIMALNAME;

Private circusanimal (String name)

{

AnimalName = name;

}

Public string toString () {

Return AnimalName;

}

}

Class zoo2

{

PRIVATE CIRCUSANIMAL ANIMAL;

Public static void main (string [] args)

{

ZOO2 z2 = new zoo2 ();

Z2.Animal = Circusanimal.tiger;

// Some Time Later ...

IF (z2.animal == circusanimal.tiger)

System.out.println ("This Circus Animal IS A Tiger!");

Else

IF (z2.animal == circusanimal.monkey)

System.out.Println ("this circus animal is a monkey!");

Else

System.out.Println ("Don't know!";

}

}

The Circusanimal class defines four constants: Tiger, Lion, Elephant, and Monkey. Each constant is initialized to a Circusanimal object.

Define a special Circusanimal constructor that is only one string variable. This string passes a private animalName field to the constructor. (I will introduce the constructor later.)

The constructor is declared as private is to ensure that the Circusanimal object created does not exceed the range of four objects that are defined into constants. You don't want to create a Circusanimal object that creates a meaningless 987324. Only the four Circusanimal constants in ZOO2 are effective.

Why define a TOSTIRING () method in Circusanimal? This method returns a String object that references the value of AnimalName. Assume that when you initialize z2.animal, call System.out.Println (Z2.Nimal) after Circusanimal.tiger, the result is that the Tiger will be output, which is given when creating a Tiger constant in the constructor of Circusanimal. System.out.println () calls the toString () method in the background to get Tiger. (I will talk about the toString () method in the subsequent column.)

Now you know how to define where the field is, you need to learn how to define and access methods.

Next: Definition method

Resources:

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

New Post(0)