In the previous tutorial, you learned the concept of object-oriented concepts. Now let's learn how to use these concepts in Java. Introduce this part of the tutorial
Create class management inheritors perform nested classes
5.1 Creating a class
This section will introduce a full description of a larger class Stack and describe all components of the class of the life cycle of the object it inherit. First introduce the constructor, then introduce member variables and methods.
Since we have already introduced how to create and use objects and how to clear the object from memory, it is now what we describe how to write classes. This section will be introduced through a small example of the LIFO (post-first out) stack to introduce the components of the class. As shown in Figure 22, the structure of the class and the identification code:
(Figure 22)
The execution of the stack uses additional objects, which is vector to store its elements. Vector is an array of objects that assigns memory space for new objects when needed. This Stack class is to store its elements by using the Vector. However, it limits the VECTOR LIFO, which means that you can only increase the element and remove the element from the top of the stack.
5.1.1 statement
Figure 22 shows two main components performed by the composition: class declarations and type entities. Class declaration defines the names of the class and other properties. The class declaration for the Stack class is relatively simple, it indicates that the class is public and its name is Stack.
Figure 23 shows the possible components of classes and describes their purposes. The required components are the Class keyword. All other components are optional. If you don't declare these optional components, the Java compiler will give a default value: Nonpublic, NonabStract, NOfinal subclasses without performing interfaces.
(Figure 23)
The following is a more detailed description of each class.
Public: This public keyword declares that the class can be used in any other class.
Abstract: Declare this class cannot be instantiated.
Final: Declare that the class cannot be inherited, ie there is no subclass.
Class NameOfClass: Keyword Class Indicates the compiler class declaration and the name of the class is NameOfClass.
Extends Super: This Extends clause thinks that Super is the parent class of the class, so the class is inserted in the classified structure.
Implements interfaces: In order to declare the class, one or more interfaces can be performed, you can use the keyword IMPLEMENT and give a list of the names of the interface executed by the class later, which are separated by commas.
5.1.2 entities
The class entity is followed by the class declaration, which is embedded in the middle of the braces {and}. The class entity contains all instance variables and declarations for class variables. In addition, the class entity also includes all the declarations of all instance methods and class methods.
5.1.3 Providing constructor for class
Categories may contain one or more constructor that provides initialization of objects created from class.
All Java classes have constructor, which is used to initialize new objects. The constructor is the same name and the name of the class. For example, the name of the STACK class is stack, and the name of the Rectangle class constructor is the name of the constructor of the Rectangle, the Thread class is Thread. The constructor of the STACK class is given below.
Public stack () {
Items = new vector (10);
}
Java supports overloading of constructor, such a class can have multiple constructor, and all the names of all constructor are the same. Below is an additional constructor defined in Stack. This constructor is based on its parameters to initialize the size of the stack.
Public stack (int initialsize) {
Items = new vector (InitialSize);
}
It can be seen from above with the same name, but they have different parameter lists. The compiler will distinguish these constructor based on the number of parameter lists and types. Typically, constructor uses its parameters to initialize new object status. When you create an object, select the constructor to see if its parameters are best reflected in the new object you want to initial. 5.1.3 Providing constructor for class
According to the number and type of the constructor parameters you pass, the compiler can decide which constructor to use. The following code compiler is known, it uses a single integer parameter:
New Stack (10);
Similarly, when you write the following code, the compiler selects a constructor without parameters or the default constructor:
New stack ();
When you write your own class, you don't have to provide a constructor for it. The system will automatically provide the default constructor. This default constructor will not complete anything. So if you want to make some initialization, you have to write some constructor for classes.
The following is the constructor of Thread's subclasses, which performs animation, sets some default values, such as frame speed, and the number of pictures, and load pictures.
Class AnimationthRead Extends thread {
Int framespersecond;
Int NumImages;
Image.
Animationthread (int FPS, INT NUM) {
Super ("AnimationThread");
THIS.FRAMESPERSECOND = FPS;
THIS.NUMIMAGES = NUM;
this.images = new image [nuMages];
For (int i = 0; i <= numimages; i ) {
.
// below reprint
.
}
}
.
}
5.1.3 Providing constructor for class
In fact, the entity of the entity with the function is similar, that is, it contains a local variable declaration, cycle, and other statements. However, the second line in the AnimationThread constructor, you will not see the constructor's constructor:
Super ("AnimationThread");
This line calls a constructor thread provided by the parent class AnimationThread. This specific Thread constructor has a string parameter, which is used to set the name of Thread. Often, constructor wants to use the initialization code written in the parent class. In fact, some classes must call their parent class constructor to make the object correctly complete the task.
The constructor of the parent class must be the first statement of the subclass constructor. Objects must first perform high-level initialization. You can specify what other objects can create an instance of how other objects can be created by using a specified specified by the constructor, and the instructions of access are as follows:
Private: No other class can instantiate this class. This class may contain a public class method that can construct an object and return, but other classes can't.
Protected: Only subclasses and classes in the same package can create its instance.
Public: Any class can create its instance.
When not explained: Only the class in the same package can create an instance.
The constructor provides a method of initializing new objects. Initialization instances and class members provide a method of initializing the initialization class and new objects by class.
5.1.4 Declaration member variables
The state of the class is given by its member variables. You can live a class of members variables in the entity of the class. Typically, you can declare the variables of the class before declaring it, although this is not necessary.
ClassDeclaration {
Member Variable Declarations
Method Declarations
}
Note here, in order to declare the variable (class member), the statement must be in the entity in the entity, not in the entity of the method. The variables declared in the physical entity are partial variables.
5.1.5 Execution Method
It is well known that the behavior of the object is performed by its method. Other objects access objects by calling it. In this section, we will have a method for the Java class. In Java, you can define a class of methods in the entity of the class to perform some behavior. Typically, you can declare the methods of classes after variables in the class entity, although this is not necessary.
Figure 24 shows the code of the PUSH method of the Stack. This method is a flash operation that puts an Object as a parameter, placed on the top of the stack and then returns it.
(Figure 24)
Just like a class, there are two main parts: method declarations and method entities. Method declare all properties of the method, such as access level, return type, method name, and parameters, as shown in Figure 25:
(Figure 25)
Method entities have code that implements method behavior. It contains Java instructions that perform methods.
Here are the declarations of the method:
A method of declaration includes the name of the method and the returned type (specified by the data type returned by the method):
Returntype methodname () {
.
}
This method statement is very basic. Methods There are many other properties, such as parameters, access control, and more.
So how do you pass the information to the method?
It may be, and the components declared in most cases the components declared are the parameters of the method. Similar to functions of other programming languages, Java methods receive parameters transmitted by the caller. These parameters provide information from the outside of the method domain to the method.
5.1.6 Controlling access to class members
When we declare the Java members, we can allow or not allow other types of objects to access these members through access instructions.
One is that the class can protect their member variables and methods accessed by other objects. Maybe you will ask this very important? Yes it is. If you write a class, it queries the data, and this database contains various secret information of the company, so there must be protection.
In Java, you can use access instructions to protect them when declaring class variables and methods. Java language supports four access levels for member variables and methods: private, protected, public, and rating.
The following table gives the access level of each access indication:
Access all private x protected x *
The first column gives whether or not the class itself can access it. From the table, you can know that the class can always access its own members. The second column gives whether or not the subclass of the class can access its member; the third column gives the class in the same package to access members. The fourth column gives all kinds of classes to access members.
Here, pay attention to a '*' at the protected / subclass cross, this is a special access, and the following tutorial will give a detailed introduction.
5.1.6 Controlling access to class members
Detailed description of various access levels:
Private
Most of the distribution level of access is private. Private members can only be accessed by the classes it define. If the external access this variable will result in a state of contradictions before and after. Or if the Private method is called by an external class, the state of the running program or the object is in a poor state. Private members are like some secrets that are not misal.
To declare a private member, just join the private key when declaring. The following class contains a private member variable and a private method:
Class Alpha {Private Int IAMPRIVATE
Private void privateMethod () {
System.out.println ("PrivateMethod");
}
}
This alpha type object can check or modify the imaprivate variable and call the privateMethod method, but other types of objects can not be, for example, the following Beta classes cannot access the IAMPRIVATE variable or call PrivateMethod because Beta is not Alpha type:
Class beta {
Void AccessMethod () {
Alpha a = new alpha ();
A.iamprivate = 10; // illegal
A.PrivateMethod (); // illegal
}
}
5.1.6 Controlling access to class members
Private
When a class tries to access a member variable it cannot access, the compiler will print an error message (as shown), the disease refuses to continue the compiler:
Beta.java: 9: Variable IAMPRIVATE IN Class Alpha Not
Accessible from class beta. // The IMAPRIVATE variable in the alpha class cannot be accessed from the Beta class.
A.iamprivate = 10; // illegal
^
1 Error // An error
At the same time, if your program tries to access a method that cannot access, it will lead to the following compiler error:
Beta.java: 12: No Method Matching PrivateMethod ()
Found in class alpha. // There is no match in the Alapha class privateMethod ()
A.PrivateMethod (); // illegal
1 Error // An error
Java's newcomers may ask if an Alpha object can access another ALPHA object's Private member. A specific example is given below. If the Alpha class contains an instance method, it compares the current alpha object (this) and another object's IAMPRIVATE variable:
Class alpha {
Private int iamprivate;
Boolean ISEqualto (alpha annetheralpha) {
IF (this.iamprivate == anotheralpha.iamprivate)
Return True;
Else
Return False;
}
}
The result is quite legal. So, the same type of object can access other private members. This is because access restrictions are only on the category level (all instances of classes) rather than on the object level (specific instance of class).
5.1.6 Controlling access to class members
(2) protected
Protected allows class itself, subclasses, and classes in the same package to access this member. You can use the protected accepted level when you are allowed by sub-access to the class to eliminate access to other unrelated classes. Protected members are like family secrets, and the family knows that it doesn't matter, but will not let out people know, isn't there a "family odor can't be exit"? Although nothing "home stink" here, it is a member of Protected.
In order to declare a protected member, use the keyword protected. First, let's take a look at how protected is the class in the same package. If the Alpha class above is now defined in a (package) package Greek, it has a protected member variable and a protected method: package Greek;
Public class alpha {
Protected Int IAMPROTECTED;
protected void protected () {
System.out.println ("ProtectedMethod");
}
}
Now, hypothesis GAMMA also declares a member of the Greek package (not a subclass of Alpha). The Gamma class can legally access the IAMPROTECTED member variable of the Alpha object and can be legally called ProtectedMethod:
Package Greek;
Class gamma {
Void AccessMethod () {
Alpha a = new alpha ();
a.iamprotected = 10; // legal
A.ProtacectedMethod (); // legal
}
}
5.1.6 Controlling access to class members
(2) protected
Let's take a study of how protected is an accessed from the subclass of Alpha:
First introduce a new class Delta, which is inherited by alpha, but it is in different packages, ie Latin. This Delta class can access IAMPROTED and ProtectedMethod, not only access to the Delta class object but also access it. The Delta class cannot access the IAMProtaced or Protected or ProtectedMethod in an object of the alpha type. AccessMethod in the following code attempts to access the imaprotected member variables in the alpha type object, which is not legal, and access to the Delta type object is legal. Similarly, AccessMethod attempts to call the protectedMethod of the Alpha object is also legal:
Package latin;
Import Greek. *;
Class delta extends alpha {
Void AccessMethod (Alpha A, Delta D) {
A.iamprotected = 10; // illegal
D.iamprotected = 10; // legal
A.Protected (); // illegal
D.Protected (); // legal
}
}
In summary, if a class is a subclass of a class containing a Protected member or they are in the same package, then this class can access the protected member.
5.1.6 Controlling access to class members
(3) Public
The easiest access indication is public. In any class, you can access the public member in any package. Only when the external object does not generate bad results, it is declared as public member. In order to declare a public member, you can use the public keyword as follows:
Package Greek;
Public class alpha {
Public int IAMPUBLIC;
Public void publicmethod () {
System.out.println ("publicmethod");
}
}
Now let's rewrite the beta class and place it into a different package, and make sure it is unrelated to Alpha: Package Roman;
Import Greek. *;
Class beta {
Void AccessMethod () {
Alpha a = new alpha ();
A.iampublic = 10; // Legal
A.PublicMethod (); // LEGAL
}
}
From the above code segment you can see that Beta can legally check and modify the IAMPUBLIC variable in the alpha class and can be legally call publicmethod.
5.1.6 Controlling access to class members
(4) Package
Use the package access level if you do not explicitly set a member to access other levels of members. This access level allows access to members in the same package. The level of access is assumed that the classes in the same package are friends who trust each other. For example, the following modified Alpha class declares a single package access to member variables and methods. Alpha is in a Greek package:
Package Greek;
Class alpha {
Int IAMPACKAGE;
Void packageMethod () {
System.out.println ("packageMethod");
}
}
This Alpha class can also access IAMPackage and PackageMethod. Alternatively, all definitions can also access IAMPackage and PackageMethod with the same class as Alpha. If Alpha and Beta are defined as part of the Greek package:
Package Greek;
Class beta {
Void AccessMethod () {
Alpha a = new alpha ();
A.iamPackage = 10; // legal
a.packageMethod (); // legal
}
}
As mentioned above, Beta can be legally accessed to access IAMPackage and PackageMethod.
5.1.7 Understanding examples and class members
The Java class can include two types of members: instance members and class members. This section will tell you how to live these two members and how to use them.
You can declare a member variable as follows, such as Afloat in MyClass:
Class myclass {
Float Afloat;
}
You declare an instance variable. Every time you create an instance of the class, the system will create a copy of the class instance for this instance. You can access instance variables for objects in an object.
Example variables are different from class variables. The system is allocated to each class, regardless of the instance created by the class. When the class is first called, the system allocates memory for class variables. All instances share the same copy of the class variable. You can access class variables through an instance or class itself.
The method is similar, class has an example method and a class method. The instance method is to operate the current object instance variable and access the class variable. Another aspect, the class method cannot access the instance variable defined in the class unless they create a new object and access them through an object. At the same time, the class method can be called in the class, you do not have to call a class method.
By default, unless other specified, the definition is defined in the class in the class. Defined in the class below has an instance variable (integer x) and two instance methods (x and setx, is the value of other objects to set and query X):
Class Anintegernamedx {
INT X;
Public int x () {
Return X;
}
Public void setx (int newx) {
x = newx;
}
}
Every time you instantiate the new object from the class, you get a new copy of the class instance variable. These copies are associated with new objects. Therefore, every time you instantiate a new AnintegeNameDX object, you get a new copy of the X's X for a connection with the AnintegeNameDX object. 5.1.7 Understanding examples and class members
All instances of the class share the same implementation of an instance method. All instances of AnintegernameDX share the same implementation of X and SetX. Note that two methods x and setx references the instance variable X of the object. But you may ask "If all instances of AnintegerNameDX share the same implementation of X and SetX, is this not ambiguous?", The answer is of course: not. In an instance method, the name of the instance variable is an instance variable that references the current object. Therefore, X and setX are equivalent to this X, and there is no need to be ambiguous.
AnintegerNameDX external object If you want to access X, you must be implemented by an a specific instance of AnintegerNameDX. If the following code segment is in the method of other objects, it contains two different anintegeNameDx type objects, and sets X as different values, then displayed:
.
Anintegernamedx myx = new anintegernamedx ();
Anintegernamedx anotherx = new anintegernamedx ();
MYX.SETX (1);
anotherx.x = 2;
System.out.println ("myx.x =" myx.x ());
System.out.println ("anotherx.x =" anotherx.x ());
.
It is worth noting that the code uses setx to set the X value of MYX, and directly assign a value to Anotherx.x. Regardless of the method, the code is to operate two copies of different X: one is included in the MyX object, and the other is included in the AnotherX object. Their output is:
MYX.X = 1
anotherx.x = 2
The above example illustrates that each instance of the class AnintegeNameDX has a copy of its own instance variable x and each X has different values.
When a member variable is declared, you can specify a variable is a class variable instead of an instance variable. Similarly, you can specify a method for class methods instead of an instance method. When you call the class definition of the variable, the system will create a copy for the class variable. All instances of the class share the same copy of the class variable. Class methods can only operate class variables, which cannot access instance variables defined in the class.
5.1.7 Understanding examples and class members
To specify a member variable is a class variable, you can use the static keyword. For example, let's modify the following anintegernamedx classes to make X variables into a class variable:
Class Anintegernamedx {
Static int x;
Public int x () {
Return X;
}
Public void setx (int newx) {
x = newx;
}
}
The result output is:
MYX.X = 2
anotherx.x = 2
The result is the same because x is now a class variable, so there is only one variable copy, which is shared by all instances of AnintegerNamedx, including MYX and Anotherx. When you call SetX in either instance, you change the value of all instances of anintergernamedx.
When defining a method, you can specify how the method is a class method instead of an instance method. Class methods can only operate class variables without accessing instance variables defined in the class. 5.1.7 Understanding examples and class members
In order to specify the method as a class method, you can use Static keywords in the method declared. Now let's change the AnintegerNameDX class, such as its member variable x is an instance variable, and its two methods are class methods:
Class Anintegernamedx {
INT X;
Static public int x () {
Return X;
}
Static public void setx (int newx) {
x = newx;
}
}
When we compile this modified Aninternamedx, the compiler gives the following error:
Anintegernamedx.java: 4: can't make a static reference to
NonStatic Variable X in Class Anintegernamedx.
Return X;
^
The reason for this error is that the class method cannot access instance variables unless the method first creates an instance of AnintergerNameDX and through it to access the variable.
The next modification of AnintegerNamedx so that the X variable is a class variable:
Class Anintegernamedx {
Static int x;
Static public int x () {
Return X;
}
Static public void setx (int newx) {
x = newx;
}
}
Now the class can be compiled, it sets their X value before creating an AnIntegerNameDX, and prints out:
MYX.X = 2
anotherx.x = 2
Another difference between instance members and class members is class members to access them in the class itself. You don't have to instantiate a class to access class members. The above code is modified:
.
Anintegernamedx.setx (1);
System.out.println ("AnintegerNameDx.x =" anintegernamedx.x ());
.
Note that you no longer need to create MYX and Anotherx. You can set X directly from AnintegerNameDX and retrieve X. And you can't process instance members like this, you can only call only instance methods from the object. You can access class variables and methods from the instance of the class or from the class itself.
5.1.7.1 Initialization instances and class members
You can use the Static Initializer and instance initializer to provide initial values for class and instance members when you declare them in class:
Class Bedandbreakfast {
Static Final Int Max_capacity = 10;
Boolean full = false;
}
However, this initialization form has the following limitations:
The initialization program can only be initialized, which can be expressed by assigning statements. The initializer cannot invoke any way to lead to an abnormality. If the initializer calls a method of generating an exception, it cannot be recovered.
If you have some initialization can't be done in the initializer, because these restrictions above, you have to place an initialization code in it elsewhere. In order to initialize the class member, place the initialization code in a static initial block. In order to initialize the instance member, the initialization code is placed in the constructor.
5.1.7.2 Using Static Initialization Block
Below is an example of a Static initialization block, as shown in Figure 2:
(Figure 26)
Note here that the Errorstrings resource beam must be initialized in the Static initialization block. This is because the error recovery must be done when it is found. At the same time, ErrorString is a class member, which is not used in the initialization in the constructor. As described above, a Static initial block starts with the Static keyword, which is a normal Java code embedded in braces {and}. Classs can have many initialization blocks and can appear anywhere in the class entity. The system ensures that the Static initialization block and the Static initial program are called in the order in which the source code is appeared.
5.1.7.3 Initialization block instance variable
If you want to initialize the instance variable and you cannot initialize in the initialization block, you can initialize in the constructor. If the erroestrings beam is an instance variable instead of a class variable, you can use the following code to initialize:
Import java.util.resourcebundle;
Class errors {
ResourceBundle Errorstrings;
Errors () {
Try {
ERRORSTRINGS = ResourceBundle.
GetBundle ("ERRORSTRINGS");
} catch (java.util.missingResourceException e) {
/ / This is an error recovery code
}
}
}
Initializing Errorstrings is now in the constructor of the class.
5.1.7.3 Initialization block instance variable
Sometimes, the class contains many constructor, and each constructor allows the caller to provide different initial values for different instance variables of the new object. For example, Java.awt.Rectangle has three constructor:
Rectangle ();
Rectangle (int Width, Int Height);
Rectangle (int X, int y, int width, int tent);
The constructor without parameters does not allow the caller to provide the initial value, while the other two constructor allow the user to set the initial value (size and origin). However, all instance variables must be initialized. In this example, the constructor completes these initialization work. For example, these three constructors are initialized:
Rectangle () {
THIS (0, 0, 0, 0);
}
Rectangle (int width, int hotht) {
THIS (0, 0, Width, Height);
}
Rectangle (int X, int y, int width, int tent) {
THIS.X = X;
THIS.Y = Y;
THIS.WIDTH = Width;
THISHEIGHT = HEIGHT;
}
The Java language supports instance initialization blocks, but it cannot be used in no record class (cannot declare constructor). The reason for the use of constructor is:
All initialization code is placed together so that the code is easier to maintain and read. The default can be processed dominate.
Programmers use constructor, even if Java's novice is the same. The instance initialization program may cause some programmers feel difficult to read the code.
5.2 Management inheritance
Review the previous tutorial, the Extends clause declares that your class is a subclass of other classes. You can specify a parent class for your class (Java does not support multiple class support), even if you remove the Extends clause from your statement, your class can also be a parent class. So, there is one or only one direct parent class in Java.
As shown in Figure 27, it is a top class, all classes inherited from this class, which is defined in Java.lang.
(Figure 27) This Object class defines and executes all kinds of behavior required in the Java system. It is a parent class of all classes.
5.3 Perform a nested class
The Java programming language allows you to define a class in another class, ie nested classes. Internal inside is a typical nested class.
Java allows you to define a class as a member of another class, such as:
Class enclosingclass {
.
Class anestedclass {
.
}
}
You can use nested classes to show and force the relationship between the two classes. When the nested class is only meaningful after embedding or when it rely on the entry-entered function, you should define a class in another class, even if you use the nested class. For example, the text mouse is only meaningful when it is in a particular text component.
As a member of the circle, nested classes have a privilege: it can access circles in a circle without restrictions, even if they are defined as private. But this privilege is not truly special, it is consistent with Private and other access indications. Access indication limits access to external members of the circle. Nested classes are in a circle into class, so it can access members into classes.
Like other members, nested classes can be declared as static. A Static nested class is called a Static nested class. Non-Static nested classes are called internal classes. Hereinafter, an example:
Class enclosingclass {
.
Static class astaticnestedclass {
.
}
Class innerclass {
.
}
} When using Static methods and variables, a Static nested class is associated with a circle. Like class members, the Static Circle Class cannot directly reference the example variables or methods defined in the circle into classes, only by reference to references. When utilizing example methods and variables, the internal class is associated with the instance of the circle into classes, and the instance variables and methods of the object can be directly accessed. At the same time, because the internal class is associated with the instance, it cannot define any Static members.
To help distinguish between classes and internal classes, it is recommended to think about the following methods. The embedded class is a grammatical relationship between two classes, that is, a class code appears in another class code. In contrast, the internal class is a relationship between two types instance, and is as follows:
Class enclosingclass {
.
Class innerclass {
.
}
}
The relationship between these two classes is given as shown in Figure 28.
(Figure 28)
You can encounter these two classes in the Java API and need to use it. But most of the nested classes you have written will be internal classes.