Java Certification Course 06

zhaozj2021-02-16  113

Chapter 6 Advanced Language Characteristics

This module discusses more object-oriented characteristics in Java programming languages.

Section 1 related issues

Discussion - The following issues are related to the materials that appear in this module:

- How to keep one class or method not being divided into subclasses or covered?

- How to expand the use of array concepts to an object?

Second source

After completing the study of this module, it should be

- Describe static variables, methods, and initial programs

- Describe Final class, methods, and variables

- List access control level

- Confirm the downgrade and explain how to move from JDK1.0 to JDK1.1 to JDK1.2

- Describe how to apply collection and reflection

- Confirm in the Java software program

- Static method and variable

- Public, private, protected and default variables

- Use Abstract class and methods

- Explain how and when to use internal classes

- Explain how and when to use interfaces

- Description == and Equals ()

Third section (static) variable

STATIC variable

Shared in all examples of instances

Can be labeled as public or private

If you are marked as public without such an instance, you can access from external access from this class.

Public class count {

Private int serialnumber;

Private statin = 0;

Public count () {

Counter ;

Serialnumber = Counter;

}

}

Sometimes I want to have a variable that can be shared in all instances of the class. For example, this can be used as the basis of an instance or tracking the number of instances that have been created.

This effect can be used to mark the variable with keyword static. Such variables are sometimes called Class Variable to distinguish between non-shared members or instance variables.

Public class count {

Private int serialnumber;

Private statin = 0;

Public count () {

Counter ;

Serialnumber = Counter;

}

}

In this example, each object created is paid to a unique number of serial numbers, starting from 1 and proceeding up. Variable Counter is shared in all instances, so when an object is constructed, the next object being created accepts an increased value.

Static variables are similar to the global variables in other languages ​​to some extent. The Java programming language does not have such a global language, but the Static variable is a single variable that can be accessed from any instance of the class.

If the Static variable is not marked into private, it may be accessed from the outside of the class. To do this, you don't need an instance of the class, you can point to it through the name.

Public class staticvar {

PUBLIC Static Int Number;

}

Public class OtherClass [

Public void method () {

INT x = staticvar.number;

}

}

Fourth Class (STITIC) method

Class (STIC) method

No instance of the class it belongs, the Static method can be called

Public class generalfunction {

Public Static Int Addup (int X, int y) {

Return X Y;

}

}

Public class usegeneral {

Public void method () {

INT A = 9;

INT b = 10;

INT C = GeneralFunction.Addup (a, b);

System.out.println ("Addup () gives" c);

}

}

When there is no instance of a special object variable, you sometimes need to access the program code. Method with keyword Static tags can be used, sometimes called Class Method. STATIC methods can be accessed by catenamers instead of reference, such as:

Public class generalfunction {

Public Static Int Addup (int X, int y) {

Return X Y;

}

}

Public class usegeneral {

Public void method () {

INT A = 9;

INT b = 10;

INT C = GeneralFunction.Addup (a, b);

System.out.println ("Addup () gives" c);

}

}

Because the Static method does not require any instance of the class to which it belongs will be called, there is no THIS value. As a result, the Static method cannot access any variables separated from the parameters of its own and STATIC variables. Attempts to access non-static variables will cause compilation errors.

Note - Non-static variables are limited to examples and can only be accessed by instance references.

Public class wroge {

INT X;

Public static void main (string args []) {

x = 9; // Compiler Error!

}

}

Import Points to Remember About Static Methods:

Main () is static because it must be sequentially accessed before any instantiation, so that the application is running.

The static method cannot be covered into non-static.

Section 5 Static Initialization Procedure

Static initialization program

In Static Block, the class can contain code that does not exist in the method program.

When the class is loaded, the static code block is only executed once.

The code that does not exist in the program body can contain this code in the Static Block class, which is completely effective. When the class is loaded, the static block code is executed only once. Different static blocks in the class are executed in the order they appear in the class.

Public class stataintinitdemo {

Static int i = 5;

STATIC {

System.out.println ("static code i =" i );

}

}

Public class test {

Public static void main (string args []) {

System.out.println ("Main Code: i ="

StaticinitDemo.i);

}

}

Will be printed:

Static code: i = 5

Main code: i = 6

Static method and data

Section 6 A complete example

1. Class myclass {

2. Static int stat = 4;

3. Static Double Statdouble = 16.0;

4. Int instint;

5. Double INSTDOUBLE;

6.

7. Public static void statmethod () {8. System.out.println ("Statint =" Statint

9. "; Statdouble =" stat Double);

10. }

11. Public static void instthod () {

12. System.out.println ("instint =" instint

13. "; INSTDOUBLE =" INSTDOUBLE);

14. }

15. Public myclass (int idarg, double doublearg) {

16. INSTINT = INTARG;

17. INSTDOUBLE = doubleARG;

18. }

19. Public static void main (string args []) {

20. Myclass instance1 = new myclass (1,2.0);

twenty one. Myclass instance2 = new myclass (3,4.0);

twenty two.

twenty three. Myclass.statmethod (); // outputs: statint = 4;

twenty four. //Statdouble =16.0

25.

26. Instance1.instmethod (); // Outputs: instint = 1;

27. //Instdouble=2.0

28. Instance1.statmethod (); // outputs: statint = 4;

29. //Statdouble =16.0

30.

31. Instance2.instmethod (); // Outputs: instint = 3;

32. //Instdouble=4.0

33. Instance2.statmethod (); // outputs: statint = 4;

34. //Statdouble =16.0

35. }

36. }

37.

Figure 6-1 is a block diagram of a MyClass class definition. This example is elaborated:

1. STIC Method and Data Single (shared) copy is because all instances of the class and the class. Access Static members can be accessed by an instance or through class itself.

2. Non-static data is limited to instances, and it can only be accessed by the non-static method of this instance. The non-static data definition objects are different from each other, and the non-static method is not the same as the behavior of each object on the basis of the non-static data they act.

Consider instance of an object of an object of imitating a special type of car. The size of the wheel is a constant for all cars of this type, which may be imitated into a static variable. The color varies depending on the object, and its behavior is also different depending on the object, and different objects are returned to different objects on the basis of non-static data it act.

Figure 6-1 MYCLASS example

Section 7 Keyword Final

6.7.1 final class

Keyword Final

Final class cannot be divided into subclasses

Final method cannot be covered

Final variable is constant

Java programming language allows keyword Final to be applied to classes. If this is done, the class cannot be divided into subclasses. For example, class java.lang.string is a Final class. This is for security reasons because it guarantees that if the method has a string reference, it is definitely a string of class string, not some other class string, this class is a String's modified subclass Because String may be changed by malicious.

6.7.2 final method

Individual methods can also be marked as Final. The method labeled Final cannot be covered. This is due to safety. If the method has an implementation that cannot be changed, and for the consistent status of the object is critical, then the method is finaly.

The method that is declared for final is sometimes used to optimize. The compiler produces a code that is directly called by the method, rather than the usual virtual method call to the runtime lookup.

Methods marked as static or private are automatically final because dynamic linkages cannot be applied in both cases.

6.7.3 final variable

If the variable is marked as Final, the result is that it becomes a constant. The value that wants to change the final variable will cause a compilation error. Below is an example of correctly defining a Final variable:

Public final int max_Array_size = 25;

Note - If the reference type (ie, any type of type of type) is marked as Final, then the variable cannot point to any other object. But it may change the content of the object, because only the reference itself is Final.

Section 8 abstract class

Abstract class

The presence of a declaration method does not implement its class called abstract class

You can mark the classes as abstractions by keyword abstract.

Public abstract class drawing {

Public Abstract Void DrawDot (int X, int y);

Public void Drawline (int X1, int y1,

INT x2, int y2) {

// Draw use the drawdot () Method repeatedly.

}

}

An Abstract class can contain non-abstract methods and variables

Sometimes in the library development, create a class that reflects certain basic behavior and declares this class, but cannot implement this behavior in this class. Instead, this method is implemented in the subclass. Other classes that know their behavior can be implemented in the class.

For example, consider a Drawing class. This class contains methods for various drawing devices, but these must be implemented in a stand-alone platform. It is impossible to access the video hardware of the machine and must also be independent of the platform. It is intended to draw which method definition should exist, but in fact, this behavior is implemented by special slave subclasses.

As the class such as the Drawing class, it declares that the presence of methods rather than implementation, and the implementation of the method of the known behavior, such a class is often referred to as an abstract class. A abstract class is declared by tagging with a keyword Abstract. A method that is declared but does not implement (ie, these without prime body or {}) must also be marked as abstraction.

Public abstract class drawing {

Public Abstract Void DrawDot (int X, int y);

Public void Drawline (int X1, int y1,

INT x2, int y2) {

// Draw use the drawdot () Method repeatedly.

}

}

An instance of the Abstract class cannot be created. However, you can create a variable, which is an abstract class and let it point to an instance of the specific subclass. There is no abstract constructor or abstract static method. The subclass of the Abstract class provides implementation for all abstraction methods in their parent class, otherwise they are also abstract classes.

Public class machinedrawing extends drawing {

Public void drawdot (int machine x, intmach y) {

// Draw the DOT

}

}

Drawing d = new machinedrawing ();

Ninth joint interface

Join

The interface is a variant of an abstract class.

In the interface, all methods are abstract.

Multiple inheritance can be obtained by achieving such an interface.

The syntax is:

Public interface transparency {

Public static final int opaque = 1;

Public static final int bitmask = 2;

Public static final int translucent = 3;

Public int GetTransparency ();

}

The interface is a variant of an abstract class. All methods in the interface are abstract, no probabilities. The interface can only define the Static Final member variable.

The advantage of the interface is that it gives the illusions of the Java technology single inheritance rules. When the class definition can only extend a single class, it can implement the required multiple interfaces.

The implementation of the interface is similar to the subclass, except that the implementation class cannot inherit behavior from the interface definition. When a class implements a special interface, it defines (ie, give the program body) all such interfaces. Then, it can call the interface to call the interface on any object of the class of the interface. Because there is an abstract class, it allows the interface name as the type of reference variable. The usual dynamic cable will take effect. The reference can be converted to an interface type or a slave interface type, and the InstanceOf operator can be used to determine whether an object is implemented.

The interface is defined with the keyword interface, as described below:

Public interface transparency {

Public static final int opaque = 1;

Public static final int bitmask = 2;

Public static final int translucent = 3;

Public int GetTransparency ();

}

Category can achieve many interfaces. The interface implemented by the class is displayed in a comma-separated list at the end of the class declaration, as shown below:

Public Class MyApplet Extends Applet IMPLEMENTS

Runnable, mouselistener {

"..."

}

The following example shows a simple interface and a class that implements it:

Interface sayhello {

Void PrintMessage ();

}

Class SayHelloImpl Implements Sayello {

Void printMessage () {

System.out.Println ("Hello");

}

}

Interface Sayhello enforces that all classes that implement it must have a method called PrintMessage, which has a VOID return type and does not enter parameters.

Join

For the following, the interface is useful:

Declaration method, expect one or more classes to achieve this method

Determine the programming interface of an object without revealing the actual program of the class

Capture of similarity between unrelated classes, not forced class

Describe the "like function" object, which can be used as the following cases to the following cases as the parameters to be called on other objects:

Declaration methods, expect one or more classes to achieve this method.

Revene an object's programming interface without revealing the actual program of the class. (It is very useful when a class of a package is delivered to other developers.)

The similarity between the capture independent class is not forced to work.

Describe the "like function" object, which can be passed as a parameter to the method called on other objects. They are a safe alternative to "function pointer" (in C and C ) usage.

Section 10 Advanced Access Control

Advanced access control

Multi-purpose

Public is yes

Protected is

Default is

Privately

Variables and methods can be in one of the four access levels; public, protected, default, or private. Category can be in public or default levels.

Variables, methods, or classes have default access, if it does not explicitly protected modifiers as part of its statement. This accessibility means that access can be from any method, of course, these methods can only be in the member class as the same package as the target.

The variables or methods of modifier protected tags are actually easier access to the default access control tag. A protected method or variable can be accessed from any of the classes, which can be members in the same package, or access from any method in any subclass. This protected access can be accessed using this protected access when it is suitable for a subclass of a class but not unrelated classes.

Table 6-1 Summary Accessibility

Table 6-1 Accessibility

Multi-purpose

Public is yes

Protected is

Default is

Privately

Protected access is even supplied to the subclass, which resides in different packages with classes with protected features.

Section 11 Downgrade

Degrade

Downgrade is an outdated constructor and method call.

Outdated methods and constructors are replaced by methods with a more standardized naming rules.

When the upgrade code, use the -Deprecation flag to compile the code:

Javac -DepRecation myfile.java

In JDK1.1, it has made significant efforts for the standardization of the method name. Therefore, in JDK1.2, a large number of class constructors and methods are time to call out. They have been simplified by the programmer's life by the method name specified by the more standardized naming rules.

For example, in the JAVA.AWT.Component class in JDK1.1:

Methods of changing or obtaining component sizes are resize () and Size ().

The method of changing or obtaining a component rectangle is reshape () and bounds ().

In java.awt.component in JDK1.0, these methods are degraded and replaced by the primary operation of the method in the SET and GET.

Setsize () and getSize ()

SetBounds () getBounds ()

Whenever you move the code from JDK1.0 to JDK1.1 or higher, or even if you use the code used in JDK1.0, it is a good idea to compile the code with the -DepRecation flag.

C: / javac -deprecation myfile.java

The -DepRecation flag will report any of the methods used in downgrade. For example, look at a practical class called DateConverter that converts the date of the MM / DD / YY format into a day: 1. package myutility;

2. Import java.util. *;

3. Import java.text. *;

4. Public Final Class DateConverter {

5.

6. Private static string day_of_the_week [] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "SaturDay"}

7.

8. Public Static String getDayofweek (string these) {

9. Int Month, day, year;

10.

11. StringTokenizer ST =

12. New StringTokenizer (thisDate, "/");

13. Month = integer.parseint (st.nextToken ());

14. day = integer.parseint (st.nextToken ());

15. Year = integer.parseint (st.nextToken ());

16. Date D = New Date (Year, Month, Day);

17.

18. Return (day_of_the_week [d.getday ()]);

19.}

20.}

When this code is compiled in JDK1.2 with the -dePRecation flag, it will be:

C: / javac -deprecation dateconverter.java

DateConverter.java: 16: Note: The constructor java.util.date (int, int, int) HAS been DepRecated.

Date D = New Date (Year, Month, Day);

^

DateConverter.java: 18: Note: The method Int getday () in class

Java.util.date has been deprecated.

Return (day_of_the_week [d.getday ()]);

^

NOTE: DATECONVERTER.JAVA Uses a Deprecated Api.please Consult The Documentation for A Better Alternative. 3 Warnings

The DateConverter class rewritten looks like this:

1. Package myutilities;

2. Import java.util. *;

3. Import java.text. *;

4. Public final class dateconverter {

5.

6. Private statçing day_of_the_week [] =

{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "SATURDAY"}; 7.

8. Public Static String getDayofweek (string these) {

9. Date D = NULL;

10. SimpleDateFormat SDF =

11. New SimpleDateFormat ("mm / dd / yy");

12. Try {

13. D = SDF.PARSE (THEDATE);

14. } Catch (parseexception e) {

15. System.out.println (e);

16. E.PrintStackTrace ();

17. }

18. // Create a Gregoriancalendar Object

19. Calendar c =

20. New Gregoriancalendar (Timezone.gettimezone ("EST"), Locale.us);

twenty one. C.SetTime (D);

twenty two. Return (day_of_the_week

[(C.Get (Calendar.day_of_week) - 1)]);

twenty three. }

twenty four. }

Here, 1.2 versions use two new classes: SimpleDateFormat, used to use any String date format and create a class of Date objects; and GregorianCalendar class to create a calendar with local time zones and venues.

Section 12 == Operator and Equals () method

== Operator and Equals () method

Equals () and == Method Decide whether the reference value points to the same object

Equals () is overwritten in the class, which is the true value when the contents and types of the two separate objects are collected.

The Object class in the java.lang package has a Public Boolean Equals (Object Obj) method. It compares whether the two objects are equal. The equals () method of the object returns TRUE only when the two references are directed to the same object.

== Operators are also equivalent comparisons. That is, for any references X and Y, when and only when X and Y are pointing to the same object, X == y is returned.

When two separate objects are compatible, String, Date, File class, and all other Override Equals () packages (Integer, Double, etc.) will return true.

For example, the equals () method in the String class returns TRUE, and the object has the same character sequence with the String object called the method only when the parameter is not NULL and is a String object.

String S1 = New String ("JDK1.2");

String S2 = New String ("JDK1.2"); method S1.Equals (S2) returns true, although S1 and S2 points to two different objects.

Section 13 TSTRING () method

TOSTRING () method

It is used to convert an object to string

Used to convert a basic type to string

The toString method is used to convert an object to a String expression. When the automatic string conversion occurs, it is used as a reference to the compiler. System.out.println () calls the following code:

Date now = new date ()

System.out.println (now)

Will be translated:

System.out.println (now.toString ());

Object class defines the default toString () method, it returns the address of the class name and its reference (usually not very useful). Many classes cover toString () to provide more useful information. For example, all packaging classes cover toString () to provide a string format that they represent. There is no such thing as a string format for debug purposes often implement toString () to return object status information.

Section 14 Internal Class

Internal class

Has been attached to JDK1.1

Allow a class definition to be placed in another class definition

Tissue classes together

The range of classes that can be accessed

Internal class, sometimes called nested classes, which are attached to JDK1.1 and higher. The internal class allows a class definition to be placed in another class definition. The internal class is a useful feature because they allow the class of logical identity to be combined together and control a class visibility in another class.

6.14.1 Internal Class Foundation

The following example represents a common method using an internal class:

1. Import java.awt. *;

2. Import java.awt.event. *;

3. Public class myframe extends frame {

4. Button mybutton;

5. Textarea mytextarea;

6. INT count ;;

7.

8. Public myframe () {

9. Super ("Inner Class Frame");

10. MyButton = New Button ("Click ME");

11. Mytextarea = new textarea ();

12. Add (MyButton, BorderLayout, Center);

13. Add (MyTextArea, BorderLayout, North);

14. ButtonListener Blist = New ButtonListener ();

15. MyButton.AddActionListener (Blist);

16. }

17. Class ButtonListener IMPLEments ActionListener {

18. Public Void ActionPerformed (ActionEvent E) {

19. Count

20. MytextArea.Settext ("Button Clicked" {21. Count "Times");

twenty two. }

twenty three. } // End of InnerClass ButtonListener

twenty four.

25. Public static void main (string args []) {

26. Myframe f = new myframe ();

27. F.setsize (300, 300);

28. F.setVisible (TRUE);

29. }

30. } // end of class myframe

The previous example contains a class MyFrame that includes an internal class ButtonListener. The compiler generates a class file, MyFrame $ ButtonListener.class, and TomyFrame.class. It is included in MyFrame.Class, which is created outside of the class.

6.14.2 How to do internal work?

The internal class can access the scope of the class nested. The accessibility of the members of the nested class is the key and useful. Access to the range of nested classes is possible because the internal class actually has an implicit reference to the external classes (such as external class "this").

PUBLIC CLASS MyFrame Extends Frame {

2. Button mybutton;

3. Textarea mytextarea;

4. Public myframe () {

5. ....................

6. ......................

7. MyFrame $ ButtonListener Blist = New

8. MyFrame $ ButtonListener (this);

9. MyButton.AddActionListener (Blist);

10.}

11. Class Myframe $ ButtonListener IMPLEments

12. ActionListener {

13. PRIVATE myframe.

14. MyFrame $ ButtonListener (MyFrame Outthisarg) {

15. OUTERTHIS = OUTERTHISARG;

16.}

17.

18. Public Void ActionPerformed (ActionEvent E) {

19. OutertHis.mytextArea.setText ("ButtonClicked");

20. ....................

twenty one. ......................

twenty two. }

23. Public static void main (String args []) {

24. myframe f = new myframe ();

25. F.setsize (300, 300);

26. F.SetVisible (TRUE); 27.

28.}

Sometimes you have to create an instance of an internal class (for example, in some other instances without THIS). Can do this as follows:

Public static void main (string args []) {

Myframe f = new myframe ();

Myframe.buttonlistener blist =

f.new buttontonListener ();

F.setsize (50, 50);

F.setVisible (TRUE);

}

6.14.3 Internal class properties

Internal class properties

Class names can only be used in a defined range unless defined names.

The name of the internal class must be different from the nested class.

Internal classes can be defined in the method.

Any variable, whether local variables or formal parameters, if the variable is marked as Final, then it can be accessed by the method in the internal class.

The internal class has the following properties:

Class names can only be used in a defined range unless used in a qualified name. The name of the internal class must be different from the nested class.

Internal classes can be defined in the method. This rule is relatively simple, and it is dominated to the variable of the nested method. Any variable, whether local variables or formal parameters, if the variable is marked as Final, then it can be accessed by the method in the internal class.

Internal classes can use the categories of the class and instance variables and local variables in the nested blocks.

The internal class can be defined as Abstract.

Attributes

Only internal classes can be declared as private or protected so that they are not accessed from external classes. Access protection does not prevent any members of the internal class from using any other class, as long as one class is nested another one.

An internal class can be implemented as an interface and is implemented by another internal class.

Automatically declared the internal class of Static to become top layers. These internal classes lose their ability to use data or variables in local scope and other internal classes.

Internal classes cannot declare any Static members; only top-level classes can declare Static members. Therefore, a member of a requirement Static member must use a member from the top level.

Note - Internal classes are often used as a convenient feature of creating event adapters. The event adapter will be discussed in the back module.

Section 15 packaging

Packaging class

Used to view basic data elements as objects, packaging classes can be used as:

Basic data type packaging class

Boolean Boolean

Byte Byte

Char char

Short short

int Int

Long Long

Float float

Double Double

The Java programming language does not regard the basic data type as an object. For example, in the basic format itself, numbers, boolean and character data are considered to improve efficiency. The Java programming language provides packaging classes to treat basic data elements as objects. Such a data element is wrapped in an object founded around them, and each Java basic data type has a corresponding Wrapper Class in the java.lang package. Each packaging class object packages a basic value.

The list of packages is as follows:

Table 6-2 Packaging

Basic data type packaging class

Boolean Boolean

Byte Byte

Char char

Short short

int Int

Long Long

Float float

Double Double

The package object can be constructed by passing the wrapped value to the appropriate constructor. E.g:

INT PINT = 500;

Integer Wint = New Integer (PINT);

Section 16 Collection API

Collect API

Collection (or container) is a single object representing an object group and is considered to be its element.

Collection of products, BITS, Stack, Hashtable, LinkedList, etc. are supported.

Collecting the API includes the interface to hold the object as the following:

Collection - a set of objects without specific order

Set - a set of objects that have not been copied

List - Order Objects Group, Allow Copy

Collection (or container) is a single object representing an object group and is considered to be its element. Collection typically handles many objects, all types have a special species (that is, they are all continued from a common parent type). Java Programming Language Support Collection Category Vector, Bits, Stack, Hashtable, LinkedList, and more. For example, the STACK implementation is advanced (LIFO), and HashTable provides an associated object array.

Collect Objects that keep the object type. This allows you to store any objects in the collection. It can also be used to retrieve it from the collection before using the object, use the correct type conversion.

Collecting the API is typically consisting of an interface to maintain an object as the following:

Collection - a set of objects without specific order

Set - a set of objects that have not been copied

List - Order Objects Group, Allow Copy

The API also includes classes such as Hashset, ArraySet, ArrayList, LinkedList, and Vector, etc., which implement them. The API also provides methods that support certain algorithms, such as sorting, binary search, minimum and maximum, and collecting, and collecting, and collecting, etc.

Seventeenth section VECTOR class

Vector class

The VECTOR class provides a method of working with a dynamic array of various elements.

Java.lang.object

└ ------- java.util.abstractCollection

└ --- java.util.abstractList

└ ---- java.util.vector

The VECTOR class provides a method of working with a dynamic array of various elements.

6.17.1

Summary

Each vector keeps a Capacity and CapacityInCrement.

Because of the additional elements, the vector is stored on the information block to increase the size of the CapacityIncrement variable.

Public Class Vector Extends AbstractList Implements List, Cloneable, Sertizable

Each vector keeps a Capacity and CapacityInCrement. Because of the additional elements to the vector, the vector is stored on the information block to increase the size of the CapacityInCrement variable. A vector capacity is always at least as large as the size of the vector (it is usually larger).

6.17.2 Constructor

Constructor

Public vector ()

Public Vector (Int InitiaLCapacity)

Public Vector (int Initialcapacity, Int

CapacityInCtrment)

The constructor of the VECTOR class is

Public Vector () - Constructs an empty vector

Public Vector (int initialcapacity) - Constructs an empty vector with concrete storage capacity

Public Vector (int Initialcapacity, Int

CapacityInCtrment) - Constructs an empty vector with specific storage capacity and concrete CapacityInCtrment.

6.17.3 variable

Variable protected int CapacityIncrement

protected int elementcount

Protected Object ElementData []

The Vector class contains the following instance variables:

Protected int CapacityIncrement - an increase amount. (If 0, each time you need to increase, the size of the buffer is twice.)

Protected int elementcount - The number of elements in the buffer.

Protected Object ElementData [] - The element stored buffer.

6.17.4 method

Below is some methods in the Vector class. Refer to the Java API to see the description of all the methods in this class.

Public final int size () - Returns the number of elements in vector. (This is different from the capacity of the vector.)

Public Final Boolean Contains (Object ELEM) - If the specified object is the value collected, it returns true.

Public Final Int IndexOf (Object Elem) - Search the specified object from the starting position and returns an index to it (or if the element is not found). It uses an object's equals () method, so if the object does not override the Object's equals () method, it is only comparing object reference, not comparing object content.

Public FinalSynchronized Object Elementat (INDEX) - Returns the element in the specified index. If Index is invalid, it throws ArrayIndexOxoutofVoundSexception.

Public Final Synchronized Void SetElementat (int index) - Replacing the specified element in the specified index in a specified object. If Index is invalid, it throws ArrayIndexOxoutofVoundSexception.

Public Final Synchronized Void RemoveElementat (INDEX) - Delete the element in the specified index. If Index is invalid, it throws ArrayIndexOxoutofVoundSexception.

Public Final Synchronized Void Addelement (Object Obj) - Additional specified objects as the last element of the vector.

Public Final Synchronized Void InsertElementat (Object Obj, INDEX) - Inserts a specified object as an element in the specified index, and all elements with equivalent or greater index. If Index is invalid, it throws ArrayIndexOxoutofVoundSexception.

6.17.5 Vector Vector Template Example:

The following templates can be used to attach different element types to the vector and print out vector elements:

Note - The method used by this program is from the classes discussed above in this module.

1. Import java.util. *;

2.

3. Public class myvector extends vector {

4. Public myvector () {

5. Super (1, 1); // Storage Capacity & CapacityIncrement

6. }

7.

8. Public Void Addint (INT I) {

9. AddElement (New Integer (i)); // addElement Requires

10. // Object Arg11. }

12.

13. Public void addfloat (float f) {

14. AddElement (New Float (f));

15. }

16.

17. Public void addstring (string s) {

18. Addelement (s);

19. }

20.

twenty one. Public void addchararray (char a []) {

twenty two. Addelement (a);

twenty three. }

twenty four.

25. Public void printvector () {

26. Object O;

27. INT length = size (); // compare with capacity ()

28. System.out.println ("Number of Vector Elements IS

" Length " and they area: ");

29. For (INT i = 0; i

30. O = Elementat (i);

31. IF (o instanceof char []) {

32. // an Array's toString () Method Does Not Print What Wewant.

33. System.out.println (String.copyValueof ((char []) o));

34. }

35. Else

36. System.out.println (O.Tostring ());

37. }

38. }

39. Public static void main (string args []) {

40. MyVector v = new myvector ();

41. INT DIGIT = 5;

42. FLOAT REAL = 3.14F;

43. Char letters [] = {'a', 'b', 'c', 'd'};

44. String s = new string ("hi there!");

45.

46. V.Addint (DIGIT); 47. V.addfloat (real);

48. V.addstring (s);

49. V.addchararray (letters);

50.

51. V.printvector ();

52. }

53. }

This program produces the following output:

$ java myvector

Number of Vector Elements IS 4 and Are:

5

3.14

Hi there!

ABCD

18 Reflection API

Reflection API

Can be used as

Construct new class instance and new array

Access and modify the fields of objects and classes

Method in calling objects and classes

Access and modify an element of an array

Java Reflection API provides a class that can be used to determine the variables and methods of a class file. Because the purpose of being used for dynamic discovery and execution code, the API can be used:

Construct new class instance and new array

Access and modify the fields of objects and classes

Method in calling objects and classes

Access and modify an element of an array

These operations are possible as long as security policies allow. Reflection API is useful if you need to run and process information. For example, if you are writing a Java software interpreter or debugger, you can use it.

19th Reflection API Characteristics

Reflection API characteristics

Java.lang.class

Java.lang.reflect.field

Java.lang.reflect.method

Java.lang.reflect.Array

Java.lang.reflect.constructor

The main features of the core reflection API of the definition classes and methods are as follows:

Java.lang.class class provides methods that allow information about classes and their fields, constructor, and methods.

Java.lang.Reflect.field provides a method that sets / get information about the fields in the class.

Java.lang.Reflect.Method provides methods, this method accesses and calls methods in class and gets their signatures.

Java.lang.Reflect.Array enables array objects from province.

Java.lang.Reflect.constructor provides reflection access to constructor.

Section 20 Reflection API Security Model

Reflection API security model

Java Security Manager is a class to control access to the core API.

When the case occurs, the standard Java programming language access control is enhanced:

Field is used to get or set a field value

Method is used to call a method

The constructor is used to create and initialize an instance of a new class.

Java Security Manager is a class to control access to the core API. When the case occurs, the standard Java programming language access control is enhanced:

Field is used to get or set a field value

Method is used to call a method

The constructor is used to create and initialize an instance of a new class.

Exercise: Work with advanced language characteristics

Practice Purpose - Use the bank account model and adopt advanced object-oriented features, such as: internal class, vector class, and interface, etc., override, compile and run three programs.

First, ready

In order to successfully complete the experiment, you must be familiar with the object-oriented concepts in this module and the front module.

Second, the task

Level 1 experiment: Modify bank account issues

1. Definitions contain only two ways deposits deposits and the interface of the WITHDRAW.

2. From the module 5, use the Personal interface to define a set of different account types and redefine the class account.java. It must be able to handle personal accounts and further divide them into two accounts. 3. Design and develop methods for providing protection. For example, if a customer has a deposit and a check account, you must ensure that the check account is protected by deposit account.

Secondary experiment: use internal class

1. Create a class called BasicArray, declare and initialize an array called THISARRAY, which contains four integers.

2. Create a class named Factorial, which contains a method of calculating its parameters.

3. Create an instance of the Factorial class from the main way of BasicArray, then call its method to calculate the steps of each of the four integers.

4. Compile and test the program.

5. Move all things in the Factorial class to the BasicArray class. Factorial is now an internal class of BasicArray.

6. Compile and test the program.

Three-level experiment: attach the Find and Delete method to the MyVector class

1. Attach the Find method to the MyVector class, which will return the location of the elements that are passed as parameters.

If this parameter is not found, let the method return -1.

E.g:

$ java myvectorfind 3.14

3.14 Is Located At Index 1

Number of Vector Elements IS 4 and Are:

5

3.14

Hi there!

ABCD

$ Java MyVectorFind C

Args [0] = C, NOT FOUND IN Vector

Number of Vector Elements IS 4 and Are:

5

3.14

Hi there!

ABCD

2. Adding the Delete method to the MyVector class, which removes all elements that match the parameters.

Method must return True or false: If delete success, true; otherwise false (element exists or does not exist in the vector).

E.g:

$ java myvectordelete 3.14

Elements 3.14 surcessFully deleded from vector.

Number of Vector Elements IS 3 and Are:

5

Hi there!

ABCD

Third, practice summary

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

Experience explanation summary application

Fourth, check the progress

Check if you can do it before you continue to learn the next module:

Describe static variables, methods, and initialization procedures

Description Final class, method and variable

List access control level

Confirm the downgrade class and explain how to move from JDK1.0 to JDK1.1, JDK1.2.

In the Java software program, confirm:

STITIC method and variable

Public, private, protected and default variables

Use Abstract class and methods

Explain how and when to use internal classes

Explain how to use when using an interface

Description = = = and Equals ()

V. Thinking

What is the characteristics of the Java programming language, so that you can directly handle the runtime error?

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

New Post(0)