Java programmer must read: Basic article (2) Object-oriented programming concept

Source: Internet
Author: User
Tags abstract execution final functions gety variables version variable
Programming | program | programmer | object | concept

If you've never used an object-oriented language before, you'll need to understand the concept before you start writing Java code. You need to understand what objects are, what classes are, how objects and classes are related, and how messages are communicated between objects. The previous section of this tutorial will describe the concept of object-oriented programming, and the following tutorial will teach you how to code this concept.

2.1 What is an object

An object is a set of software for related variables and methods. Software objects are often used to mimic some objects around us in the real world. object is the key to understanding object-oriented technology. Before you study, you can look at real-life objects, such as dogs, tables, televisions, bicycles, and so on. You can see that objects in the real world have two common characteristics: they all have states and behaviors. Dogs, for example, have their own state (name, color, fertility, starvation, etc.) and behavior (such as wagging the tail, etc.). The same bike also has its own status (such as current gear, two wheels, etc.) and behavior (such as braking, acceleration, deceleration, change of position, etc.).

The software object is actually the shape of the real world object, because it has the same state and behavior. A software object uses one or more variables to maintain its state. A variable is a data item that is named by a user identifier. A software object uses its methods to perform its behavior. Method is a function (subroutine) associated with an object.

You can use software objects to represent objects in the real world. You might want to use an animated program to represent a real-world dog, or a bike that can be used to control an electronic bike to represent the real world. Similarly, you can use software objects to sculpt abstract concepts, such as an event that is a common object used in a GUI window system, which can represent a user's response to a mouse button or a key on the keyboard.

Figure 1 is a public visual representation of a software object.

(Figure 1)

The state and behavior of the software object can be expressed in variables and methods in the object. The software object of a real-world bicycle is to have a variable that indicates the current state of the bicycle: 20mph, its current position is third gear. These variables are known as instance variables because they contain states for special bike objects, and in object-oriented technology, special objects are called instances.

As shown in Figure 2, is the bicycle styling as a software object.

(Figure 2)

2.1 What is an object

In addition to variables, software bikes also have the means to brake, change the pedal pace, and change the gears. These methods are known as instance methods because they check or change the status of special bike instances.

The object graph above shows that the object's variables form the center of the circle. The method is located around the variable and hides the core of the object from other objects in the program. The method of protecting methods to wrap an object's variables is called encapsulation. This object graph is the representation of object ideal and the final goal of object-oriented system designers. But this is not the whole story. Usually, for some practical reason, an object might expose some of its variables or hide some methods. In the Java programming language, an object can specify one of four types of access levels for variables and methods. This access level determines which objects and classes can access variables or methods. Accessing variables and methods in Java can be converted to control access to the member functions of the class. Encapsulation of related variables and methods to a concise software set is a simple and powerful way to provide software developers with two main benefits:

Modularity: The source code of an object can be written and maintained independently of other object sources. Similarly, objects can be easily passed through the system. You can give your bike object to other objects and it will still work properly.

Information hiding: If an object has a common interface, then other objects can communicate with it. This object can maintain private information and methods that can be changed at any time without affecting other objects that are resistant to it. So you don't have to understand the mechanics of gears in a bicycle to use it.

2.2 What is the message

The interaction between software objects and communication is the use of messages.

A single object is usually not very useful. Instead, an object is usually a larger program or application that contains many other objects. By interacting with these objects, programmers can gain higher-order functionality and more complex behavior. If your bike does not use it, it is a pile of aluminum alloy and rubber, it does not have any activity. It is only useful when there are other objects that interact with it.

The interaction and communication of software objects with other objects is achieved by sending them to other objects. When object A wants object B to execute the method in a B, object a will message to object B. As shown in Figure 3.

(Figure 3)

Sometimes, the receiving object needs more information as it can correctly know what to do. For example, when you want to change the gears of a bicycle, you have to point out which gears. This information is passed as a parameter to the information. As the reality shown in Figure 4, a message consists of three components:

1. Objects addressed to messages (Yourbicycle)

    1. Name of the method to execute (changegears)
    2. All parameters required by this method (Lowergear)

(Figure 4)

The above three components are given sufficient information to perform the appropriate method for the recipient's object. No further information or context is needed.

The message provides two important benefits:

1. The behavior of an object is expressed through its methods, so message passing supports all possible interactions between objects.

    1. objects do not need to send and receive messages to other objects on the same process or on the same machine

2.3 What is a class

A class is actually a prototype of a type of object that defines variables and methods.

In the real world, you often see many objects of the same type. For example, your bike is just one of many bikes in the real world. With object-oriented technology, we can say that your bike is an example of a Bicycle object class. Usually, bikes have some status (current gear, two wheels, etc.) and behavior (change gears, brakes, etc.). However, the status of each bike is independent and different from other bicycles.

When manufacturers make bicycles, manufacturers use the common characteristics of bicycles to make many bicycles according to the same blueprint. If making a bicycle is going to produce a new blueprint, the efficiency is too low.

In object-oriented software, as well, many objects of the same kind can be used to share some features, such as rectangles, employee records, video clips, and so on. Just like the bicycle manufacturer, you can use the same kind of objects to be similar to the fact that you can create a blueprint for these objects. The software blueprint for an object is called a class.

The class of bicycles needs to define some instance variables to include the current stall, current speed, and so on. This class defines and provides an implementation method for instance methods that allow cyclists to change gears, brakes, and change the tempo of pedals, as shown in Figure 5:

(Figure 5)

When you create a bike class, you can create any bike object from this class. When you create an instance of a class, the system allocates memory for the object and the instance variables. Each instance is defined in the class for a copy of all instance variables. As shown in Figure 6:

(Figure 6)

In addition to instance variables, classes also define variables for the class. A class variable contains information that is shared by all instances of the class. For example, suppose all bicycles have the same number of stalls. In this example, you define an instance variable to hold the number of stalls. Each instance will have a copy of the variable, but the values are the same in each instance. In such cases, you can define a class variable to contain the number of stalls so that all instances of the class share the variable. If an object changes a variable, it changes all objects of that class. Class can also define class methods. You can call the class method directly from the class, but you must invoke the instance method in a particular instance. As shown in Figure 7.

(Figure 7)

2.4 Instance and class members

2.4.1 Understanding instances and class members

The following is a detailed discussion of examples and class members, involving variables and methods as well as class variables and methods:

You declare a member variable in such a way that there is a float type of afloat in the class MyClass:

Class MyClass {

float afloat;

}

So you declare an instance variable. Each time you create an instance of a class, the system creates a copy of each instance variable of the class for the instance. You can access the object's instance variables from the object.

The instance variable is not the same as the class variable, and the class variable is declared using the amount of static modification. Regardless of how many instances the class creates, the system assigns class variables to each class variable. The memory that the system allocates for a class variable occurs when it first invokes the class. All instances share the same copy of class variables for the class. You can access class variables either through an instance or through the class itself.

Their approach is similar: your class can have instance methods and class methods. An instance method operates on an instance variable of the current object and accesses the class variable. Alternatively, the class method cannot access the instance variables defined in the class unless they create a new object and access them through the object. Similarly, class methods can be invoked in a class, and you do not need an instance to invoke a class method.

By default, a member of a definition in a class is an instance member unless the other member is specified. The class defined below has an instance variable with an integer x, two instance methods X and Setx, which set the other objects and the value of the query X.

Class Anintegernamedx {

int x;

public int x () {

return x;

}

public void SetX (int newx) {

x = newx;

}

}

Each time you instantiate a new object from a class, you can get a copy of the instance variable for each class. These replicas are related to the new object. So, each time you instantiate a new Anintegernamedx object from this class, you get a new copy of the new Anintegernamedx object.

All instances of a class share the same practice of an instance method; All Anintegernamedx instances share the same execution of X and Setx. Note here that two methods X and Setx refer to an object's instance variable x. But, you might ask: if all Anintergernamedx share x and setx the same execution, will it create ambiguity? The answer is, of course: No. In an instance method, the name of an instance variable refers to an instance variable of the current object, if the instance variable is not hidden by a method parameter. So in X and Setx, X is equivalent to this x, without causing confusion.

2.4 Instance and class members

2.4.1 Understanding instances and class members

For an object outside Anintegernamedx, if you want to access x, it must be implemented through a specific Anintegernamedx instance. If the code fragment is in the other object's method. It creates two different types of anintegernamedx, it sets X to different values, and then displays them:

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 ());

Note here that the code uses SETX to set the value of X for MYX, and directly assigns a value to anotherx.x. Regardless of the method, the code operates on two different x replicas: one contained within the MYX object and the other contained in the Anotherx object. The output is implemented with the following code fragment:

myx.x = 1

anotherx.x = 2

The code above shows that each instance of a class Anintegernamedx has its own copy of the instance variable x and each x has its own value.

When declaring a member variable, you can specify that the variable is a class variable rather than an instance variable. Similarly, you can specify that the method is a class method rather than an instance method. The system creates a copy of a class variable the first time the class is called to define the variable. All class instances share the same copy of the class variable. Class methods can manipulate only the class variables, and they cannot access the instance variables defined in the class.

2.4 Instance and class members

2.4.1 Understanding instances and class members

To specify that a member variable is a class variable, you can use the static keyword. For example, we can modify the Anintegernamedx class above so that the x variable is now a class variable:

Class Anintegernamedx {

static int x;

public int x () {

return x;

}

public void SetX (int newx) {

x = newx;

}

}

Now set their x values and display different outputs:

myx.x = 2

anotherx.x = 2

This time the output is different because X is now a class variable, so there is only a copy of this variable, which is shared by all instances of Anintegernamedx, including Myx and Anotherx. When you call Setx in other instances, you can change the value of x for all instances of Anintegernamedx.

Similarly, when we declare a method, you can specify that the method is a class method rather than an instance method. A class method can only operate in a class variable and cannot access all instance variables defined in the class.

To specify a method as a class method, you can use the static keyword at the method declaration. Next, we modify the Anintegernamedx class again so that 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 you want to compile this version of Anintegernamedx, the compiler will display the following error: Anintegernamedx.java:4: Can ' t make a static reference to

nonstatic variable X in class Anintegernamedx.

return x;

^

These errors occur because the class method cannot access the instance variable unless the method first creates an instance of the Anintegernamedx and accesses the variable through it.

2.4 Instance and class members

2.4.1 Understanding instances and class members

Let's revise the Anintegernamedx to make the x variable a class variable:

Class Anintegernamedx {

static int x;

static public int x () {

return x;

}

static public void SetX (int newx) {

x = newx;

}

}

Now set the value for X and print out the x values:

myx.x = 2

anotherx.x = 2

Again, we change x by MYX and change it to another instance of Anintegernamedx.

Another difference between instance members and class members is that class members can be accessed from the class itself. You do not have to instantiate a class to access its class members. Let's write a piece of code to access X and setx directly from the Anintegernamedx class:

. . .

Anintegernamedx.setx (1);

System.out.println ("anintegernamedx.x =" + anintegernamedx.x ());

. . .

It is worth mentioning that you do not have to create MYX and Anotherx now. You can set X and directly Anintegernamedx the class to retrieve X. You cannot use instance members to handle it, you can invoke an instance method from only one object and access the instance variable only from the object. You can access class variables and methods from instances of classes or from classes themselves.

2.4 Instance and class members

2.4.2 initialization instances and class members

The following is an example of initializing instances and class members:

You can use the static initializer and the instance initializer to provide initialization values for class and instance members when you define them in the class:

Class Bedandbreakfast {

static final int max_capacity = 10;

Boolean full = false;

}

This is not a problem for the original data type. Sometimes, it can be used to create arrays and objects. But this initialization form has its limitations, as follows:

1. The initialization program can only perform initialization that is expressed with an assignment statement.

    1. The initialization program cannot invoke any method that contains an exception error.
    2. If the initialization program calls a method that contains an exception error, it cannot perform an error recovery.

If you have some initialization to complete, some may not be implemented in the initialization program because there is one of the above limitations, at which point you have to place the initialization code at will. To initialize the class member, place the initialization code in the static initialization block. In order to initialize an instance member, the initialization code is placed in the constructor.

2.4 Instance and class members

2.4.3 Static initialization block

Let's talk about static initialization blocks.

Here's an example, as shown in Figure 8:

(Figure 8)

The Errorstrings source code must be initialized in the static initialization block. This is because error recovery must be performed only when the source code is not found. At the same time, Errorstrings is a class member that cannot be initialized in a constructor. In the previous example, a static initialization block starts with the static keyword, and the Java code is enclosed in braces "{}".

A class can have many static initialization blocks, which can appear anywhere in the class. The system guarantees that the static output block and the static initialization program are invoked in the order in which they are in the source code.

2.4 Instance and class members

2.4.4 Initialize Instance members

If you want to initialize an instance variable and cannot handle it at the variable declaration, you can only initialize the class in the constructor. If Errorstrings is an instance variable rather than a class variable, you can initialize it by using the following code:

Import Java.util.ResourceBundle;

Class Errors {

ResourceBundle errorstrings;

Errors () {

try {

Errorstrings = ResourceBundle.

Getbundle ("errorstrings");

catch (Java.util.MissingResourceException e) {

Error Recovery code here

}

}

}

Now the code initializes the errorstrings for the class in the constructor.

Sometimes, a class contains many constructors and each constructor allows the caller to provide initialization values for different instance variables of the new object. For example, Java.awt.Rectangle has the following three constructors:

Rectangle ();

Rectangle (int width, int height);

Rectangle (int x, int y, int width, int height);

The Rectangle () constructor does not have any arguments, so it cannot provide initialization values for the user size or origin and size, while the other two constructors allow the user to set the initial value.

2.4 Instance and class members

2.4.4 Initialize Instance members

However, all instance variables (origin and size) must be initialized. In this example, the class often has a constructor to complete all the initialization. Other constructors call this constructor and provide it with parameters or default values. For example, here are the three constructors described above, which are initialized as follows:

Rectangle () {

This (0,0,0,0);

}

Rectangle (int width, int height) {

This (0,0,width,height);

}

Rectangle (int x, int y, int width, int height) {

this.x = x;

This.y = y;

This.width = width;

This.height = height;

}

Java language Support instance initialization block, you can use it with ease. Constructors are recommended for initialization here for the following three reasons:

1. All initialization code is in one place, making the code easier to maintain and read.

    1. The default value can be cleared to know.
    2. Constructors are widely known to Java program designers, including relatively new Java program designers, and instance initializers cannot, and he can cause confusion among other Java programmers.

2.4 Instance and class members

2.4.5 Objects and classes

You may notice that objects and classes look very similar. In the real world, the distinction between classes and objects is often a source of confusion for programmers. In the real world, it is clear that classes cannot be the objects they describe. However, it is difficult to differentiate between classes and objects in software. Part of the reason is that software objects are only electronic models in the real world or abstract concepts. But also because objects are often sometimes referred to as classes and instances.

2.5 What is inheritance

A class can inherit state and behavior from its parent class. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs.

Generally speaking, objects are defined in terms of class. You can already know many objects from its class now. Even if you know, if I tell you it's a bike, you know it has two wheels and pedals and so on. Object-oriented systems are more in-depth, allowing classes to be defined in other classes. For example, mountain bikes, racing cars and tandem bicycles are all kinds of bicycles. In object-oriented technology, mountain bikes, racing cars and tandem bicycles are all subcategories of bicycles. Similarly, bicycles are the parents of mountain bikes, racing cars and tandem double bikes. This parent-child relationship can be as shown in Figure 9:

(Figure 9)

Each subroutine inherits the state from the parent class. Mountain bikes, racing cars and tandem double bikes share these states: speed and so on. Similarly, each subclass inherits classes from the parent's methods, mountain bikes, racing cars, and tandem double bikes that share these behaviors: braking, changing foot speed, and so on.

2.5 What is inheritance

However, subclasses cannot be limited by the state and behavior provided by the parent class. Subclasses can add variables and methods to variables and methods that inherit from the parent class. For example, a tandem double bike has two seats, which is not in its parent class.

Subclasses can also overload inherited methods and provide special execution methods for these methods. For example, if you have a mountain bike with an extra gear set, you can reload the gears to make it possible for cyclists to use these new gears.

Nor can you be limited to one level of inheritance. The hierarchical structure of an inheritance tree or class can be very deep. Methods and variables are progressively inherited. In general, the more you have in the hierarchy, the more behavior you have.

If the object class is at the top of the hierarchy, each class is its descendants (either directly or indirectly). A type of object retains a reference to any object, such as a class or an instance of an array. Object provides the behavior that is required to run on a Java virtual machine. For example, all classes inherit the object's ToString method, which returns a String representing the object.

Now, why do we use inheritance, and what are the benefits of that? Some of the benefits are:

1. Subclasses provide special behavior that is not in the parent class. By using inheritance, programmers can reuse code in the parent class more than once.

    1. A programmer can perform a parent class, called an abstract class, to define the total behavior. This abstract parent class can define and partially execute the behavior, but the vast majority of the parent classes are undefined and not executed. Other parts are implemented by programmers to implement special subclasses.

2.6 What is an interface

An interface is a contract that collects methods and constant forms. When a class executes an interface, it promises to declare that all methods are executed in that interface.

An interface is a device or a system that is an unrelated entity for interaction. According to this definition, remote control is an interface between you and the TV, while English is the interface between two people, and the behavior agreement that enforces in the military is the interface between different equivalence persons. In the Java language, an interface is a device that is used to interact with other objects. An interface may be similar to a protocol. In fact, other object-oriented languages have interface functionality, but they invoke their interface protocols.

The bike class and its class hierarchy define what a bicycle is. But bicycles interact with the real world in other ways, for example, in warehouses where bicycles can be managed by an inventory process. An inventory procedure does not care what kind of management project as long as the project provides a certain information, such as price and tracking number. Instead of forcing the class to relate to other unrelated items, the inventory procedure establishes a communication protocol. This protocol consists of constants and method definitions contained in an interface. This inventory interface will define (but not execute) methods to set up and get retail prices, specify tracking numbers, and so on.

In order to operate in the inventory procedure, the bicycle class must comply with this protocol when executing the interface. When one executes an interface, the class adheres to all the methods defined in the interface. As a result, bicycles provide execution for these settings and to obtain retail prices and to specify tracking values, and so on.

You can use interfaces to define a protocol for a behavior that can be executed by any class in the class hierarchy. The main benefits of the interface are a few things:

1. Do not use the artificial forcing class relation to intercept the similarity in the irrelevant class.

    1. A method that declares one or more classes that you want to execute.
    2. Exposes the object's programming interface without exposing the object's class.

2.7 How to translate these object-oriented concepts into code

This section will show you the code that creates objects, executes classes, sends messages, creates a parent class, and executes an interface.

Here is an applet (an applet is a program written in the Java programming language) that can run on a Web browser that is compatible with the Java platform, such as HotJava or Netscape Navigator, called ClickMe. As shown in Figure 10, when you click anywhere in the box, a red dot appears.

(Figure 10)

Tip: The applet above needs to be JDK1.1. If you use an older browser that does not support JDK1.1, you will not be able to run this applet. Instead, you need to look at this page in a 1.1 browser, such as HotJava, JDK Applect Browser (appletviewer), or a version of Netscape Navigator and Internet Explorer.

Here is a specific explanation for this applet.

The ClickMe applet is a relatively simple program, so its code is much shorter. However, if you don't have much programming experience, you can find that the code is not so easy. We don't ask you to immediately understand every problem in the program, and this tutorial is not very detailed. The purpose here is to expose some source code to you and to connect with the concepts and techniques you have just learned. You will learn more about it later in the tutorial.

2.7 How to translate these object-oriented concepts into code

2.7.1ClickMe source code and applet label

To compile this applet you need two source files: Clickme.java and Spot.java. To run this applet you will need to use this applet tag to create an HTML file:

<applet code= "Clickme.class" width= "height=" ></applet> where the source code for the Clickme.java is: Import Java.applet.applet;import java.awt.*;import java.awt.event.*;p ublic class ClickMe extends applet implements MouseListener {private spot spot = null;private static final int RADIUS = 7;public void init () {Addmouselistener (this);} public void Paint (Graphics g) {//Draw a black border and white background g.setcolor (color.white); g.fillrect (0, 0, GetSize (). Width-1, GetSize (). HEIGHT-1); G.setcolor (Color.Black); g.drawrect (0, 0, GetSize (). Width-1, GetSize (). height-1);//Draw Red dots g.setcolor ( color.red); if (spot!= null) {G.filloval (Spot.x-radius, Spot.y-radius, RADIUS * 2, RADIUS * 2);} public void mousepressed (MouseEvent event) {if (spot = "=" null) {spot = new spot (RADIUS);} Spot.x = Event.getx (); spot.y = Event.gety (); repaint ();} public void mouseclicked (MouseEvent event) {}public void mousereleased (MouseEvent event) {}public void mouseentered ( MouseEvent event) {}public void mouseexited (MouseEvent event) {}} and the source code for Spot.java is:public class Spot {public int size;public int x, y;public spot (int intSize) {size = Intsize;x = -1;y =-1;}}

Then load the Web page into the browser or Appletviewer tool. And make sure that all the necessary files are in the same directory. As shown in Figure 11:

(Figure 11)

Objects in the 2.7.2 ClickMe applet

There are many objects in this applet. The two most obvious are: the applet itself and the red dots.

The browser creates the applet object when it encounters an applet tag in the HTML code that contains the applet. This applet tag provides the name of the class from where the Applet object was created. In this example, the name of this class is ClickMe.

Clickme.applet will create an object to draw a point on the screen. Each time you click the mouse in the applet, the applet will move the red dot by changing the x and Y coordinates of the object. This point is not drawn by itself, it is drawn by the applet, it is based on the information contained in the Point object.

In addition to the two obvious objects, there are also some unseen objects. There are three objects representing three colors (black, white, red) and event objects that represent the action of the user clicking the mouse, and so on.

Classes in the 2.7.3ClickMe applet

Because the object representing the dots on the screen is simple, let's take a look at this class called spot. It declares three instance variables: the size of the point radius, the x-coordinate that contains the current horizontal position of the point, and the y-coordinate of the current vertical position of the containing point:

public class Spot {

Instance variables

public int size;

public int x, y;

Constructors

Public Spot (int intSize) {

size = IntSize;

x =-1;

y =-1;

}

}

In addition, the class has a constructor that initializes a new object created by the class. Constructors have the same name as the class. This constructor initializes the variables for all three objects. The initialization value for size is provided by the seat parameter at the time of the call. The x and Y variables are set to-1, where-1 is designed to allow the point to be on the outside of the screen at the beginning, creating a false visual effect.

This applet creates a new Point object when the applet is initialized. Here is the code for the Applet class:

Private spot spot = null;

private static final int RADIUS = 7;

...

Spot = new Spot (RADIUS);

The first line declares a variable named spot, which is the spot data type, and initializes the variable to null. The second line declares an integer variable, named radius, whose value is 7. The last line is to create an object. The new keyword allocates memory space to the object. Spot (RADIUS) invokes the constructor described above and passes the RADIUS value so that the size of the point object is set to 7. The left figure shown in Figure 12 represents the spot class, while the right-hand one represents the spot object.

(Figure 12)

Messages in the 2.7.4ClickMe applet

As you know, object A can use messages to request object B to do something, and a message has three components:

1. Objects addressed by the message

    1. The name of the execution method to execute
    2. Any parameters that the method requires

The following two lines of code are available in the ClickMe applet:

G.setcolor (Color.White);

G.fillrect (0, 0, GetSize (). Width-1, GetSize (). height-1);

All two messages are from the applet to the object named G. Where G is a graphic object, it knows how to simply draw some shapes or text on the screen. This object provides an applet when the browser instructs the applet to draw. The first line of the above code sets the color to white, and the second line fills a rectangular area of the specified size, and its color is white. As shown in Figure 13, it is a three component of a message:

(Figure 13)

Inheritance in the 2.7.5 clickme applet

In order to run in a browser, the object must be an applet. This means that the object must be an instance of the class that derives from the applet class provided by the Java platform.

The ClickMe applet object is an instance of a ClickMe class, which is declared like this:

public class ClickMe extends Applet implements MouseListener {

...

}

The above statement produces a subclass of the applet. ClickMe inherits many of the functions of the parent class, including initialization, starting and ending by the browser, drawing in the browser area, and registering with the mouse events received. In addition to these features, the ClickMe class also implements the following functions: its drawing code in the Paint method, initialization code must be in the Init method, and so on.

public void init () {

...//Add ClickMe initialization code here

}

public void Paint (Graphics g) {

...//Add ClickMe Paint code here

}

Interfaces in the 2.7.6 ClickMe applet

The ClickMe applet responds to mouse clicks by displaying a red dot in the mouse click. If the object wants to notify the mouse to click, the Java Platform Event system requires the object to perform the MouseListener interface. This object must be registered as a mouse listener as well.

This MouseListener interface declares five different kinds of log workers, each of which uses a different mouse event when the mouse is clicked. When the mouse is clicked, or when the mouse is moved outside the applet, and so on.

Here is the complete code for the ClickMe applet. Where mousepressed is the handling of mouse events:

import" java.applet.applet;import; Import java.awt.event.*;p ublic class ClickMe extends Applet implements MouseListener {private spot spot = Null;private STA Tic Final int RADIUS = 7;public void init () {Addmouselistener (this);} public void Paint (Graphics g) {//Draw a black border and a white background g.setcolor (color.white); g.fillrect (0, 0, GetSize (). Width-1, GetSize (). HEIGHT-1); G.setcolor (Color.Black); g.drawrect (0, 0, GetSize (). Width-1, GetSize (). height-1);//Draw a point g.setcolor ( color.red); if (spot!= null) {G.filloval (Spot.x-radius,spot.y-radius,radius * 2, RADIUS * 2);}} public void mousepressed (MouseEvent event) {if (spot = "=" null) {spot = new spot (RADIUS);} Spot.x = Event.getx (); spot.y = Event.gety (); repaint ();} public void mouseclicked (MouseEvent event) {}public void mousereleased (MouseEvent event) {}public void mouseentered ( MouseEvent event) {}public void mouseexited (MouseEvent event) {}}

2.8 Problem and practice of object-oriented concepts

The tutorials in this section test your understanding of objects, classes, messages, and so on, and we do this by doing some exercises and answering some questions.

2.8.1 problem

You can use API documentation to answer these questions:

1. The ClickMe applet uses color.red to set the paint color to red. What other colors can be used like this?

    1. How do I set the color to purple (purple)?

2.8.2 Practice

Now, use the knowledge you learned from the API documentation to modify the ClickMe applet. In order to compile this program, you also need to Spot.java files. The specific modifications are as follows:

1. Modify this applet to draw a green box instead of a red dot.

    1. Modify this applet to display your name in purple instead of a red dot.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.