Third to talk about object-oriented properties in Java language

xiaoxiao2021-03-06  58

Course index

[Before class thinking] 1. What is an object? What is a class? What is a package? What is an interface? What is internal class? 2. What are the characteristics of object-oriented programming? What are their features? 3. Do you know that Java language does a special feature in object-oriented programming?

Difficulties: 1. Understand method overload and method rewriting, do not confuse the use of both. 2. Use of class variables and class methods. 3. The use of the interface. 3.1 Object-Oriented Technology Foundation

3.1.1 Object-Oriented Basic Concepts Object-Oriented Basic Ideological Object-Oriented is an emerging programming method, or a new programming specification (Paradigm), its basic idea is to use objects, classes, inheritance, Basic concepts such as packages, messages are programmed. Software systems are constructed from things (ie, objects) existing in the real world, and use human natural thinking as possible in the system configuration. Developing a software is to solve some problems, the business scope involved in these issues is called the software problem. Its application is not only software, but also computer architecture and artificial intelligence.

1. The basic concept of objects is an entity used in the system to describe objective things, which is a basic unit constituting the system. An object consists of a set of services that operate on this group of properties.

Active object is a set of properties and a set of packages of a set of services, where at least one service does not need to receive messages (called active services). 2. The basic concept class of the class is a collection of a set of objects with the same attributes and services, which provides a unified abstract description for all objects belonging to this class, including both attributes and two main parts. In an object-oriented programming language, the class is a separate program unit, which should have a class name and include the attribute description and service description two main parts.

3. news

The message is the service request sent to the object, which should include the following information: The object identity, service identity, input information, and answer information are available. Service is often referred to as a method or function.

3.1.2 Object-Oriented Basic Characteristics

1. The encapsulation encapsulation is to combine the object's properties and services into an independent identical unit, and consist of the internal details of the object, including two meaning: ◇ Combine all the properties of the object and all services together, form an indivisible Independent unit (ie object). ◇ Information hidden, that is, the internal details of the object, and form a boundary [or form a barrier], only the limited external interface is associated with the outside. The principle of encapsulation is reflected in the software that requires that some parts other than the object cannot access the internal data (attribute) of the object, thereby effectively avoiding external errors to "cross-infection", making software errors locally, Greatly reduce the difficulty of check-in and misconduct.

2. The inheritance special class object has its own properties and services, called a special class inheritance.

A class can be a special class of a plurality of general classes, which inherits attributes and services from a plurality of general classes, which are called multi-inheritance.

In Java language, usually we call a general class as a parent class (Superclass, a super class), special type as subclass (Subclass).

3. Polymorphism of polymorphisms refers to a different data type or a different behavior that can have different data types after the attribute or service defined in the general class is inherited. This makes different semantics in the same attribute or service in a general class and its special classes. For example: "Draw" method, "elliptical" and "polygon" of "Geometric Graphics" are subclasses of "geometric map", and their "drawing" method is different. 3.1.3 Object-Oriented Program Design Method OOA-Object Oriented Analysis Object - OOD-Object Oriented Design Object-Oriented Design Object ORIENTED IMPLEMENTATION Object-Oriented Implementation 3.2 Object - Oriented Characteristics of Java Language 3.2. Category 1 is an important composite data type in Java, which is the basic element of the Java program. It encapsulates the status and method of an object, which is the original shape of this type of object. A class's implementation includes two parts: class declarations and categories

1. Class Declaration: [PUBLIC] [Abstract | Final] Class classname [extends superclassname] {...} where the modifier public, abstract, final illustrates the properties of the class, classname is the class, superclassname is the parent of the class. The name of the class, InterfaCenameList is the list of interfaces implemented by the class. 2. The category is defined as follows: Class classname {[public | protected | private] [static] [final] [TRANSIENT] [Volatile] Type Variablename; // Member Variables [PUBLIC | Protected | Private] [static] [Final | Abstract ] [Native] [Synchronized] Returntype methodname ([paramlist]) [THROWS ExceptionList] {statements} // member method} 3. The statement of member variable members is as follows: [public | protected | private] [static] [final] [TRANSIENT] [Volatile] Type VariableName; // member variable wherein static: static variable (class variable); relative to instance variables Final: Constant Transient: Temporary variables, used for object archiving, serialization of objects, serialization of the object, VOLATILE: contribute variable, shared 4 for concurrent threads. The implementation of the member method method includes two parts: method declarations and methods. [PUBLIC | Protected | Private] [Static] [Final | Abstract] [Native] [Synchronized] ReturntyPE MethodName ([paramlist]) [THROWS ExceptionList] // Method Declaration {Statements} // Method Body Method Declaration Meaning: Static: Class method, can call the Abstract: Abstract method by class name, no method final: method cannot be overridden Native: Integrated other languages ​​SYNCHRONIZED: Controlling multiple concurrent threads access ◇ Method statement: Method name, return type and external parameters. The type of the parameter can be a simple data type or a composite data type (also known as reference data type). For simple data types, Java implements values ​​for values, method receiving parameters, but cannot change the value of these parameters. If you want to change the value of the parameter, use the reference data type because the reference data type passes to the method is the address of the data in the memory, and the operation of the data can change the value of the data. Example 3-1 illustrates the difference between the simple data type and the reference data.

[Example 3-1] Import java.io. *; public class passtest {float ptvalue; public static void main (string args []) {int val; passtest pt = new passtest (); VAL = 11; system.out. Println ("Original Int Value IS:" VAL); Pt.Changeint (VAL); // Value Parameter System.out.Println ("Int ValueAfter Change IS: VAL); / * Value parameter value modification, There is no value of the value of the value * / pt.ptValue = 101f; system.out.println ("Original PtValue IS: Pt.PtValue); Pt.ChangeObjValue (PT); // Reference Type Parameters System.out.println ("PtValue After Change IS:" Pt.PtValue); / * Reference parameter value modification, change the value of reference parameters * /} public void change (int value) {value = 55; // In-way The parameter is modified} public void changeObjvalue (passtest ref) {ref.ptValue = 99f; // Internally modified the reference parameters}} ◇ Method body method is the implementation of the method, which includes local variable declarations and All legitimate Java instructions. The role of the local variable declared in the method is inside the method. If local variables are the same name with the member variable of the class, the member variables of the class are hidden. In order to distinguish between parameters and members variables, we must use this. THIS ---- uses the current object in one method, which is the object that calls the method. The return value must be consistent with the return type, or identical, or its subclass. When the return type is an interface, the return value must implement the interface. 5. Method Overloading method overload refers to multiple methods to enjoy the same name, but the parameters of these methods must be different, or the number of parameters is different, or the parameter type is different. The return type cannot be used to distinguish the method of overload. The distinction between parameter type must be sufficient, for example, cannot be the same simple type, such as INT and long. The compiler determines the method currently used based on the number and type of the parameters.

6. Construction method ◇ Construction method is a special method. Each class in Java has a constructor to initialize an object of the class. ◇ Construction method has the same name as the class name, and does not return any data types. ◇ Overload is often used in the construction method. ◇ Construction method can only call from the New operator

3.2.2 Object class instantiation can generate an object, and an object interacts through message delivery. Message delivery activates the method of the specified object to change its status or make it generate a certain behavior. An object's life cycle includes three phases: generation, use, and elimination.

The object's clearance does not present reference to an object, the object becomes a useless object. Java's garbage collector automatically scans the dynamic memory of the object, collects and releases the objects that are not referenced as garbage. System.gc (); system.exit (); // Terminate The Current JVM When the system memory is exhausted or called system.gc () requires garbage collection threads to run synchronously with the system. 3.2.3 Object-Oriented Characteristics The Java language has three typical object-oriented properties: encapsulation, inheritance and polymorphism. 1. In the encapsulation Java language, the object is a package of a set of variables and related methods, where variables indicate the state of the object, and the method indicates the behavior of the object. The modular and information hidden by the encapsulation of the object. Implement information hidden in the class in a certain access to a member of the class. ◇ j 的 j j 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 不同,. 1) A member of the Private class is limited to Private, which can only be accessed by this class itself. If a class constructor is declared as Private, other classes cannot generate an instance of the class. 2) Members of any access rights not adding to the default class belong to the default (default) access status: Friend, can be accessed by this class itself and the class in the same package. 3) The Protected class is limited to a Protected member, which can be accessed by this class itself, its subclass, its subclass (including subcategories in the same package) and all other classes in the same package. 4) The public class is defined as a member of Public, can be accessed by all classes. [Table 3-1] Comparison of the scope of limits in java

Same class

Same package

Subcounds of different packages

Different bags

Private

*

DEFAULT

*

*

protected

*

*

*

public

*

*

*

*

2. The inheritance is reused by inheritance. All classes in Java are obtained by directly or indirectly inheriting the java.lang.Object class. The class obtained by inheritance is called subclasses, and the class inherited is called a parent class. Subclasses cannot inherit the members variables and methods of access to visitors in the parent class. Subclasses can rewrite the method of parent class, and naming the member variables with the parent class. However, Java does not support multiple inheritance, namely a class from multiple superclatrifies. ◇ The rewriting of the hidden and methods of member variables can change the status and behavior of the parent class into their own status and behavior by hiding the members variables of the parent class and the method of rewriting the parent class. For example: class superclass {int x; ... void setX () {x = 0;} ...} Class Subclass Extends superclass {int x; // hide the parent class variable x ... Void setX () {// Rewrite the father Class SETX () x = 5;} ... Note: The method of rewriting in the subclass and the way to be rewritten in the parent class must have the same name, the same parameter table and the same return type, just a function The body is different. ◇ SUPER JAVA is enabled by Super Java to implement access to parent class members, and Super is used to reference the parent class of the current object. SUPER's use has three situations: 1) Access the parent class hidden member variable, such as: super.variable; 2) Call the method of being rewritten in the parent class, such as: super.method ([paramlist]); 3) call The constructor of the parent class, such as: super ([paramlist]); [Example 3-5] Import java.io. *; class superclass {int x; superclass () {x = 3; system.out.println ("in Superclass: x = " x);} void dosomething () {system.out.println (" in superclass.dosomething () ");}} class subclass extends superclass {int x; subclass () {super (); / / Call the texture method of the parent class x = 5; // Super () To place the first sentence in the method System.out.Println ("in subclass: x =" x);} void dosomething () {Super. DOSMETHING (); // Call the method of the parent class system.out.println ("in subclass.dosomething ()"); system.out.println ("super.x =" super.x "sub.x =" X);}} public class inheritance {public static void main (string args []) {subclass subc = new subclass (); subc.dosomething ();}}

3. Polymorphisms In Java Language, polymorphism is embodied in two aspects: dynamic polymorphism (compiled time polymorphism) and method rewriting by method overloading (compile time polymorphism) and method rewriting achieved dynamic polymorphism (running polymorphism). 1) Compile time polymorphism in the compilation phase, which is the overloaded method, and the compiler will staticly determine the corresponding method according to the different parameters. 2) Running polymorphisms Sub-objects can be used as a parent class object due to subclasses inheriting all parent classes (except for private). Wherever the program uses the parent class object, you can use a sub-object instead. An object can call a subclass by reference to an instance of a subclass. ◇ Calling principle of rewriting method: Java runtime system determines which method of call according to the instance of calling this method. An example of a subclass, if the subclass rewrites the method of the parent class, the method of running the subclass when the system is runtime; if the subclass inherits the method of the parent class (not rewriting), the runtime system calls the parent class. Methods. In Example 3-6, the parent class object A reference is an instance of subclasses, so the CallME method of subclass B is called when Java runtime. [Example 3-6] Import java.io. *; class a {void callme () {system.out.println ("INSIDE A's Callme () Method");}} Class B Extends A {Void Callme () {system .out.println ("INSIDE B'S Callme () Method");}} public class dispatch {public static void main (string args []) {a a = new b (); a.callme ();}} ◇ Method Principles should follow when rewritten: 1) After rewritten, the method cannot be more stringent access to the way (the same). 2) Remote method does not have more exceptions to the method of rewriting. 4. Other ◇ Final Keyword Final keywords can be modified, and the members variables and members of the class, but Final's functionality is different. 1) Final modified member variable: final modified variable, it becomes a constant, such as Final Type VariableName; when modified member variables, the initial value is defined, and it cannot be modified in the future, while the modification of local variables will not be required. 2) Final modified member method: final modification method, then this method cannot be rewritten in subclass of Final ReturNType MethodName (paramlist) {...}

3) Final Class: Final Trunge Class, the class cannot be inherited Final Class FinalClassName {...} Instance members and class members with static keywords can declare class variables and class methods, their formats are as follows: Static Type Classvar; Static ReturntyPE ClassMethod {paramlist}) {...} If Static keyword modifications are not available in the statement, declare the instance variable and instance method. 1) Example variables and instance variables of each object each object allocate memory, access these instance variables through this object, and different instance variables are different. Class variables are only assigned memory only when generating the first object, and all instance objects share the same class variable, each instance object changes to class variables, affects other instance objects. Class variables can be accessed directly through class names without having to be mailed to an instance object, or can access class variables through instance objects. 2) Example method and class method example method can operate the instance variable of the current object, or operate the class variable, the instance method is called by the instance object. However, the class method cannot access instance variables and can only access class variables. The class method can be called directly by the class name, or the instance object is called. This or super keyword cannot be used in the class method. Example 3-7 is an example of example membership and class members. [Example 3-7] Class Member {static int classvar; int instancevar; static void setclassvar (int i) {classvar = i; // instancevar = i; // type method can not access instance variable} static int getClassvar () {Return Classvar;} void setInstancevar (INT i) {classvar = i; // instance method can not only access class variables, but also instance variables instancevar = i;} int getInstancevar () {Return Instancevar;}} public class membertest {public static void Main (string args []) {member m1 = new member (); member m2 = new member (); m1.setClassvar (1); m2.setclassvar (2); system.out.println ("m1.classvar =" m1.GetClassvar () "m2.classvar =" m2.getClassvar ()); m2.setinstancevar (11); m2.setinstancevar (22); system.out.println ("m1.instancevar =" m1. GetInstanceVar () "m2.instancevar =" m2.GetInstanceVar ());}}} ◇ 类 java.LANG.Object class java.LANG.Object The root of the class hierarchy in the Java development environment, all other classes are direct These are inherited indirectly. This class defines some of the most basic status and behavior. Below, we introduce some common methods.

Equals (): Compares whether two objects (references) are the same. GetClass (): Returns the representation of the class corresponding to the object run, so that the corresponding information can be obtained. TOSTRING (): String representation used to return objects. Finalize (): Used to clear the object before garbage collection. Notify (), NotifyAll (), WAIT (): Synchronization in multi-threaded processing. 3.2.4 Abstract and interface

1. In the abstract class Java language, with the Abstract keyword to modify a class, this class is called an abstract class, which is called an abstract method when modifying a method with the Abstract keyword. The format is as follows: Abstract Class AbstractClass {...} // Abstrained Abstract Returntype AbstractMethod ([paramlist]) // Abstract method The abstract class must be inherited, the abstract method must be rewritten. Abstract methods only need to declare, no need; abstract classes cannot be instantiated, abstract classes do not have to include abstract methods. If the class contains an abstract method, the class must be defined as an abstract class.

If a class inherits an abstract class, the abstract method of the abstract class must be implemented, otherwise the subclass must declare to Abstract. 2. The interface interface is one of the abstract classes, only the definition of constants and methods, without the implementation of variables and methods, and its method is an abstract method. It is reflected in the following aspects: ◇ Implement the same behavior of unrelated classes through the interface without considering the relationship between these classes. ◇ 指 Individual methods that need to be implemented through the interface. ◇ Learn the interactive interface of the object through the interface without having to understand the class corresponding to the object. 1) Definition of the interface of the interface includes interface declarations and interfaces. The format of the interface declaration is as follows: [public] interface interface {...} Extendsuperinterface] {...} Extends clause is basically the same, and the difference is that an interface can have multiple parent interfaces, separated by commas, and one Class can only have a parent class. The interface includes a constant definition and method defining a constant definition format: Type Name = value; the constant is implemented in multiple class shares of the interface; with the properties of Public, Final, Static. You can only declare a constant in the interface, and the variable cannot be declared. Method Body definition format is: (with public and Abstract attributes, you cannot declare "Returnty MethodName ([paramlist]);

Note: In the implementation class of the interface, the implementable interface method must be declared as public because the method defined in the interface is public (default). Therefore, its implementation must be declared as public. Otherwise, compile will not pass. 2) Implementation of the interface in the declaration of the class to represent a class using an interface, and you can use the constant defined in the interface and all methods defined in the interface must be implemented. A class can implement multiple interfaces, separated by commas in the Implements clause. 3) The interface of the interface type is used as a reference type. Any instance of a class that implements the interface can be stored in a variable of the interface type, and the method in the interface implemented by these variables can be accessed. 3.2.5 Internal Class

1. The definition and use of internal classes: Internal classes are classes in the internal nested definition of a class, which can be a member of other classes, or within the internal definition of a statement block, you can also define anonymous inside the expression. The internal class has the following characteristics: ◇ Generally used within the class or statement block, you must give a complete name when referenced to it externally. Name cannot be the same as the class name containing it. ◇ You can use the statics and instances of the class containing its classes, or the local variables of the method thereof can also be used. ◇ You can define Abstract. ◇ can be declared as private or protected. ◇ If it is declared as static, it becomes a top layer, and local variables cannot be used again. ◇ If you want to declare any Static member in Inner Class, the Inner Class must declare to static. Example 3-8] import java.awt *;. Import java.awt.event *;. Public class TwoListenInner {private Frame f; private TextField tf; public static void main (String args []) {TwoListenInner that = new TwoListenInner ( ); That.go ();} public void Go () {f = new frame ("two listener example"); F.Add ("North", New Label ("Click and Drag the Mouse"); TF = New TextField (30); F.Add ("South", TF); F.AddmouseMotionListener (new mousemotionrandler ()); f.SetSize (300, 300); F.SetVisible (TRUE) PUBLIC CLASS MOUSEMOTIONHANDLER EXTENDS MOUSEMOTIONADAPTER {public void mousedragged (mouseEvent E) {string s = "mouse Dragging: x =" E.GETX () "y =" E.Gety (); tf.settext (s) }}} Public class mouseeventhandler Extends mouseadapter {public void mouseentered (mouseEvent E) {string s = "the mouse entered"; tf.settext (s);} public void mouseexited (MouseEvent E ) {String s = "the mouse left the building"; tf.settext (s);}}}

Note: The Add method of the Frame is from its ancestral CONTAINER class, the AddMouseMotionListener and the AddMouseListener method come from its ancestor class Component, the parameter of the ADDMOUSELISTENER method is a mouselistener interface, and the MouseAdapter class is a class that implements the MouseListener interface. It can be seen that the response of the graphical interface to the external event is to achieve 2 of the Listener implemented. The definition and use of anonymous classes: Anonymous class is a special internal class that contains a complete class definition in an expression. Through the modification of the GO () part of the Some statement in Example 6-7, we can see the use of anonymous classes. Public void Go () {f = new frame ("two listener example"); F.Add ("North", New Label ("Click and Drag the Mouse"); TF = New TextField (30); f.add ("South", TF); F.AddmouseMotionListener (new mousemotionrandler () {/ * defines an anonymous class, the class name is not explicitly given, just this class is the subclass of the MouseMotionraler class * / public void mousedragged (MouseEvent e) {string s = "mouse Dragging: x =" E.GETX () "y =" E.Gety (); tf.settext (s);}}); f.addmouseristener (new mouseeventhandler () ); F.setsize (300, 300); f.setVisible (true);} 3. Advantages of internal classes: ◇ Advantages: Save the size of the bytecode file generated after compilation] Disadvantages: Make the program structure unclear exercises:

1: Modeling cannot be prototype from the parent class to the subclass, only from the subclass to the parent class. Otherwise, it can be passed when compiled.

Such as: subclass sc = new subclass (); baseclass bc = (baseclass) sc; --- is correct

Baseclass bc = new baseclass (); subclass sc = (subclass) bc; --- is a wrong

BaseClass BC = new subclass () is also correct, and the method body executed when the method in which the method in the BC is the method body of the subclass, but the method must simultaneously exist at the same time in the subclass, the parent class. And there is no in the parent class, but can not call bc.submethod ();

If two classes are inherited in the same class (must be directly inherited, otherwise, these two classes can assign each other, such as: Panel and Frame inherited in Container, so Panel P = new frame (); and Frame f = new panel () is correct,

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

New Post(0)