Program Transfer Related Statement Break In switch, the Break statement is used to terminate the execution of the Switch statement, so that the program starts from the first statement after the entire SWITCH statement. n In Java, you can add a label for each code block, and a code block is usually a piece of code enclosed in braces {}. The format of the marking is: BlockLabel: {CodeBlock;} NBREAK statement is the second usage of the NBREAK statement is to jump out of the block it specifies and execute at the first statement following the block. Break BlockLabel; Program Transfer Related Statements Continue §Continue Statement Used to end this loop, skipped in the following statement, then perform the determination of the termination condition to determine whether to continue cycling. For the for statement, before performing the determination of the termination condition, you must first execute iterative statements. Its format is: continue; § You can also use the Continue to jump to the outer loop indicated by the brackets, the format is Continue Outerlable;
Program Transfer Related Statement RETURN § RETURN statement exits from the current method, returns to the statement that calls the method, and continues the execution of the next statement following the statement. Return statement has two formats: return expression; // When the method needs to return a type of data; // When the method's return type is VOID, § a single RETURN statement is placed in the middle of the method, because the compilation error is generated because The subsequent statements will not be executed. If you really need to exit, you can use the RETURN statement to embed certain statements (such as if-else), exit when all statements in the method are not implemented.
Exception processing statement: try-catch-finally, throw When the program is designed, the incorrect generation is inevitable. How to handle errors? Have the error to Who deal? How do the program recover from errors? This is a problem that any programming language must face and solve. The Java language is incorrect through exception (Exception). We will introduce exceptions and processes in the sixth lecture.
4. Java class definition specification JAVA is an object-oriented programming language with basic properties of object-oriented technology. Class is the main content of the expression of the face in Java, which is an important data type in Java, which is the basic element of the Java program. We will detail the definition of the class in the next lesson and the concepts related to the objects, packages, interfaces, etc.
5. The Java array is in the Java language, an array is the simplest composite data type (reference data type). Array is a collection of order data. Each element in the array has the same data type, which can uniquely determine the elements in the array with a unified array name and subscript. An array has a one-dimensional number of groups and a multi-dimensional array. We will introduce in the later courses.
6. Java Development Class Bank Composition Java provides a rich standard class to help program designers write programs more easily and easily, these standard classes consist of classes, mainly: java.lang java.awtjava.applet java.awt.Imagejava .awt.peer java.iojava.net Java.util In addition to java.lang, the remaining classes are not required by the Java language.
1) Java.LANG This class contains classes that must be required when defined Java languages, which can access Java's inside. Any Java program will automatically introduce this package. The classes include: Object class: The most primitive, most important class in Java, each Java class is its subclass, which implements basic methods that must have each class. § Basic Type Packaging: Boolean, Character, Number, Double, Float, Integer, long. § String class: string class. § MATH class: Collection of mathematical functions. § Execute thread: class Thread, threadgroup, interface runable. § Exception, Error, Interface Throwable, Error. (1) Java.lang§ Run environment: You can access the external system environment by class Runtime and System. The two common functions of the System class are to access standard input / output streams and error flows, exiting the program. § Other classes: Interface Cloneable, runtime class, etc. (2) Java.applet Java Applet is a major charm of Java programming, and the Java.applet class package provides an APPLET's running mechanism and some ways to write Applets.
(3) Java.awt This class is a unified interface of various window environments (AWT represents Abstract Windows Toolkit, which is an Abstractable Toolkit), which makes created, such as windows, menus, scroll bars, text districts, buttons, and complex The elements of the graphical user interface (GUI) such as selecting the box are very easy. (4) Java.awt.image package can load and filter bitmap images in a manner independent of the device. (5) java.awt.peer java.awt.peer is a collection of peer-to-peer objects of all AWT components. Each interface provides a basic method of machine-related methods, and AWT uses these methods to implement GUI, without having to care. Machine or operating system.
(6) Java.io Java's input / output mode is fully based on the stream. Flow is one-way flow from one place to another, which can be attached to files, pipes, and communication links. Many streams defined in the Java.io class package are organized by inheritance, including some streams of files to access files on the local file system. (7) Java.NET Java.NET class package is used to complete the network-related features: URL, WWW connection, and more common Socket network communication. (8) Java.util Java.util class includes some practical classes and useful data structures, such as Dictionary, hashtable, stack, vectors, and enumeration (Enumeration) Wait. CHAP3. Java and object-oriented technology 1
1, object-oriented concept
The so-called object-oriented methodology is to enable us to analyze, design, and implement a system approach us to understand the method of understanding a system. Including: § Object-Oriented Analysis § Object-Oriented Design (OOD, Object-Oriented Design) § Object-Oriented Program Design (OOPL, Object-Oriented Program) Object-oriented technology mainly around the following Concept: object, abstract data type, class, type hierarchical (subclass), inheritance, polymorphism. § The object object has two levels of concepts. The objects in real life refers to an entity of a considerable world; and the object is a set of variables and related methods, where variables indicate the state of the object, the method indicates the behavior of the object. .
The objects in real life can be abstract, mapped into objects in the program. Objects are described in the program, which is described by an abstract data type, which is called class.
Class Car {Int Color_Number; Int Door_Number; Int Speed; Void Brake () {...} void spetedup () {...} void solutiondown () {...}}
§ Class (Class) class is a "basic prototype" that describes the object, which defines the data that can be owned by a class of objects and can be completed. In object-oriented programming, classes are the basic unit of the program. Similar objects can be merged into the same class, just like the variables in the traditional language. The object in the program is an instance of the class, is a software unit, which is constructed of a set of structured data and a set of operations thereon.
N variable: refers to the state of the object. n method: refers to the functional unit of the object. N Message Software Objects interacts and communicates by passing messages between each other, a message consists of three parts: Objects Accepting a message 2. Receive objects to take the method 3. The parameters required by the method
n An example class hello {private string s; public void showString () {system.out.println (s);} public void change "{s = str;}} n In the program operation object is one of the class Example. n Create an object: hello obj = new hello (); N calling method: obj.showstring (); Why use the class with simple data types to represent the concept of the concept in the real world. Limitations. For example, INT data indicates a date concept, you need to use 3 variables: int Day, Month, Year; if you want to represent 2 people's birthday, use 6 variables: int mybirdhday, mybptermonth, mybpteryear; int Yourbpterday, YourBptermonth YourBpterhyear;
There are not only variables in the class, but also the methods defined by the related operations. Packing the variables and methods in a class, you can hide the member variables, and the access to class members can be made by way, and the classes can be protected from illegal modification.
Class birthdate {public int day, month, year; public int tomorrow () {...}} Birthdate mybirth, you.
Birthdate date; Know the current date object, date the date of the second day: date.day = date.day 1; if Date.day is already 31, the results are illegal. You can define a member method tomorrow (), and ask the date object on the second day. When the external date is obtained, as long as the call: Date.Tomorrow (); N package package combines all components of the object, the package definition
The program how to reference the data of the object, and the package actually uses the method to hide the data, control the degree of modification and access data for the class.
The N sub-class class is a class defined as an expansion or correction of another class. § Inheritance is the method and variable defined in the parent class, just like they belong to the subclass itself.
Class Car {Int Color_Number; Int Door_Number; INT Speed;
Public void push_break () {...} public void add_oil () {...}}
Class Trash_car extends car {double amount;
PUBLIC VOID FILL_TRASH () {...}}
The overlay of the n method redefines the method in the parent class in the subclass.
Class Car {Int Color_Number; Int Door_Number; INT Speed;
Public void push_break () {speed = 0;} public void add_oil () {...}} class trash_car extends car {Double Amount
Public void fill_trash () {...} public void push_break () {speed = speed - 10;}}}} n method overload (polymorphism) at least two methods in the same class use the same name, but there is a different Parameters.
2, class, methods and variables in Java
Stringent definition and modifying word [Class modified word] Class class name [EXTENDS Parent Class Name] [IMPLEMENTS Interface Name List] {
Variable definition and initialization;
Method definition and method;
}
Class modified word: [public] [Abstract | Final] default method for Friendly
§ Definition and modification of member variables
[Variable Modification] Variable data type variable name 1, variable name 2 [= variable initial value] ...
[public | protected | private] [static] [final] [transient] [volatile]
The type of member variable can be any data type in Java, including simple types, classes, interfaces, arrays. The member variable in a class should be unique.
§ Method and variable definition and modification word
[Method Modified] Return Type Method Name (Parameters 1, Parameters 2, ...) [THROWS EXCEPTIONLIST] {... (statements;) // Method: Method}
[public | protected | private] [static] [final | abstract] [native] [synchronized]
The return type can be any Java data type, and when a method does not need to return a value, the return type is VOID. The type of parameters can be a simple data type, or the reference data type (array, class or interface), the parameter transfer method is the value transfer. The method is the implementation of the method. It includes a declaration of a local variable and all legal Java instructions. The role of the local variable is only inside the method. Class Cardemo {public static void main (string args []) {car democar = new car (); democar.set_number (3838); democar.show_number ();}} class car {int car_number;
Void set_number (int car_num) {car_number = car_num;}
Void show_number () {system.out.println ("My Car No. IS: car_number);}}
§ The generation of object (1) object generates an object via the new operator; for example: car democar; democar = new car (); (2) The construction process of the object u is the object opening space, and the object's member variable is default Initialization; u The initialization of the member variable; ü Call the construction method.
§ Object (3) The use of objects of objects is implemented by a reference type variable, including the member variables and methods of reference objects, and the access and method of access and method of variables can be implemented by operators. For example: birthdate date; int day; // Reference Date's member variable day date.tomorrow (); // call Date method Tomorrow ()
§ Inheritance
Class car {int car_number; void set_number (int car_num) {car_number = car_num;}
Void show_number () {system.out.println ("My Car No. IS: car_number);}}
class TrashCar extends Car {int capacity; void set_capacity (int trash_car_capacity) {capacity = trash_car_capacity;} void show_capacity () {System.out.println ( "My capacity is:" capacity);}}
Class Cardemo {public static void main (string args []) {trashcar demotrashcar = new trashcar (); demotrashcar.set_number (4949); demotrashcar.show_number ();
Demotrashcar.Set_capacity (20); demotrashcar.show_capacity ();}}
Car is a parent class, trashcar is a subclass. The two methods in the trashcar are inherited, and two new methods are added. Inheritance is another basic feature of object-oriented programming language, and the code can be reused by inheritance. The class obtained by inheritance is subclass, the class being inherited is a parent class, and the parent class includes all classes that are directly or indirectly inherited. Multiple inheritance is not supported in Java. By adding an Extends clause in a class: Class SubClass Extends Superclass {...} This class is a subclass of java.lang.Object if the extends clause is default. Subclasses can inherit the visits in the parent class to set the member variables and methods of public, protected, default, but cannot inherit the member variables and methods of the access rights for private.
N When choosing to inherit? A good experience: "B is a a a?" If so, let B make a subclass of A.
§ Class method coverage is covered by redefining the methods existing in the parent class in the subclass.
Class Car {Int Color_Number; Int Door_Number; INT Speed;
Public void push_break () {speed = 0;} public void add_oil () {...}}
Class Trash_car extends car {double amount;
Public void fill_trash () {...} public void push_break () {speted = speed - 10;}}
§ Calling method for the method of rewriting, the Java runtime system decides which method call to select according to the type of the instance of calling the method.
Public class democar {public static void main (string args []) {car ACAR = new trash_car (); acar. push_break ();}}
Here, the PUSH_BREAK () method in class trash_car will be called.
§ Methods The principles that should follow (1) The override method cannot be more stringent access to the covered method. (2) Covering methods cannot produce more exceptions than covered methods.
§ Overloading method of class methods means that multiple methods can enjoy the same name. However, the parameters of these methods must be different, or the number of parameters is different, or the parameter type is different. For example, to print different types of data, int, float, string, do not need to define different names: Printint (int); printfloat (float); PrintString (String). Using method overload, you only need to define a method name: println (), receive different parameters: println (int); println; println; string);
§ The overloader of the polymorphic method is a polymorphism. In addition, the polymorphism can also refer to the place where the parent class object needs to be used in the program, can be replaced by sub-objects. For example: public class employee extends object {...} public class manager extends Employee {...}: Employee E = new manager (); // legal statement
§ The hiding of the member variable can be hidden with the members variable: set the variable method setvariable (), get the variable method getVariable (). Class sample {int x; ... Void setx (int var) {x = var;} int getX () {return x;} ...
§ The identification of the object state is in the Java language, providing an instance of operator instanceof to determine if an object belongs to a certain class.
Public void method (EMPLOYEE E) {if (e instanceof manager) {... // do something as a manager} else if (e instanceof contractor) {... // do something as a contractor} else {... // do something else} }
3, Java namespace and access rules
N Each class has its own namespace, that is, the species and its methods and variables can know each other in a certain range, which can be used. For classes: NABSTRACT classes cannot directly produce objects that belong to this class; NFinal classes cannot be inherited by any other classes (security considerations); NPUBLIC classes can not only be used by other classes in the same package, other packages The class can also be used; the NFRIENDLY class can only be used by other classes in this package.
n For member variables and members of the class, its application range can be limited by the application of certain access rights. Non-child private ★ default ★ ★ ★ PUBLIC ★ ★ ★ public ★ ★ ★ public ★ ★ ★ PUBLIC ★ ★ ★
§Public: Any other class, the object can access the data of the variable as long as you can see this class, or use the method. § protected: The same class, the same package can be used. The class of different packages must be the subclass of such classes. § PRIVATE: No other class access and calls are allowed. § Friendly (there is no modified word front): The class that appears in the same package can directly use its data and methods. N The same variable name in the subclass is the same as the parent class, the variable of the parent class is covered.
Class a class b extends a {{int DATA_A = 3; int DATA = 5;}} class c extends b {void print_out () {system.out.println ("DATA =" DATA_A); System.out.Println "A.data_a =" a.data_a); system.out.println ("b.data_a =" b.data_a);}}
Class demo {public static void main (string args []) {c = new c (); c.Println_out ();}}
§ This is until - Final§ Final Before class, the standard is that the class cannot be inherited. § Final prevented the method from being covered before the method. §Final defines a constant before the variable.
§ These variables and methods that belong to the class --StaticStatic before variables or methods, indicating that they are class, called class methods (static methods) or class variables (static variables). If there is no Static modification, it is an example method and instance variable. Class variables share all instances
Class abcd {char data; static int share_data;} Class demo {Abcd A, B, C, D;
§ The survival of class variables does not depend on objects, which is equivalent to the role of global variables in the C language. Other classes can not be accessed by instantiating.
Public class staticvar {public static int number = 5;} public class otherclass {public void method () {int x = staticvar.number;}}
§ Class Method is equivalent to a global function in the C language, and other classes can be called to call them without instantiation.
Public class generalfunction {public static int address {returnix x y;}} public class useGeneral {int a = 9; int b = 10; int c = generalfunction.addup A, b);}}
§ The method in the same class can access member variables of the class; § A class method can only access its local variables.
§ Incorrect reference class stating {string mystring = "hello"; public static void main (string args []) {system.out.println (mYString);}} error message: NonStatic Variable MyString Cannot Be Reference from A Static context "System.out.println (MyString);". Why isn't it correct: Only the object's method can access the variable of the object.
Solution 1. Change the variable to class variable class staticerror {static string mystring = "hello"; public static void main (string args []) {system.out.println (mYString);}}
2. Create a class of instances Class NostaticError {String MyString = "Hello"; public static void main (string args []) {NostaticError NoError; noerror = new NostaticError (); system.Out.println (noerror.mystring); }
4, abstract classes, interfaces and packages in Java
§ The abstraction method is modified with an abstract method to modify a class, which is called an abstract class; when a method is modified with Abstract, the method is called an abstract method. The abstract class must be inherited, the abstract method must be rewritten. Abstract classes cannot be instantiated directly. Therefore, it is generally an overclass of other classes and is just the opposite of the Final class. Abstract methods only need to be declared without implementation. Classes that define abstract methods must be an abstract class. Abstract Returntype AbstractMethod ([paramlist]);
§ Two Class Circle and Rectangle, Complete Calculation Calculation Class Circle {Public Float R; Circle (Float R) {THIS.R = R; // This refers to "This object"} public float area ()} * r * r;}} Class Rectangle {public float width, height; rectangle (float w, float h) {width = W; // Height = H;} public float area ()} public float area () {Return Width * Height;}} It is assumed to have several Circle, as well as several Rectangle, I hope to calculate their total area, straightforward practice is to put them in two arrays, with two cycles, plus one addition, this practice It is not beautiful. If there are other shapes: Triangle, Ellipses, etc., the above method seems to be "cumbersome". We want to have a unified representation, such as using a array shape [], accept all shapes, then use: for (i = 0; i
Class Rectangle Extends Shape {Public Float Width, Height; Rectangle (Float W, Float H) {width = W; // This is not required to "this" height = h;} public float area () {Return Width * height;}} The interface interface is a collection of method definitions and constant values. In essence, the interface is a special abstraction class, which only contains only constant and methods definitions, and there is no way to implement. ¨ The same behavior of the unrelated class can be achieved through the interface without considering the hierarchical relationship between these classes. ¨¨ The method of multiple classes need to be implemented through the interface can be specified. ¨ You can understand the interactive interface of the object through the interface without understanding the class corresponding to the object.
Definition of the interface: [public] interface interface interface interfabename [extends superinterfacelist] {... // constant definition and method definition}
Use the Implements clause to represent a class to use an interface. You can use the constant defined in the interface and all methods defined in the interface must be implemented. Multiple inheritage can be achieved by using an interface, that is, a class can implement multiple interfaces, separated by commas in the Implements clause. The role of the interface is similar to the abstraction, only the prototype is defined, and the content is not directly defined. The methods and variables in the interface must be public. Interface collection {int max_num = 100; void add (object obj); Object Find (Object Obj); int currentcount ();}
Class Fifoqueue Implements Collection {Void Add (Object Obj) {...} Void delete (Object Obj) {...} Object Find (Object Obj) {...} int currentcount () {}} package (package) due to Java compilation Generate a zona file for each class, and the file name is the same as the class name, so the class of the same name may conflict. In order to solve this problem, Java provides a package to manage class space.
The package is equivalent to the library function in other languages. Packing Java with a package statement to packet a class in a Java source file into a package. The Package statement is the first statement of the Java source file indicating the package where the classes defined in the file are indicated. (If this statement is available, it is specified as an ignorant package). Its format is: package pkg1 [.pkg2 [.pkg3 ...]]; Java compiler The package corresponds to the directory management, Package statement of the file system, is used. To specify the level of the directory. Package myclass.graphics; class square {...;} class circle {...;} Class Triangle {...;
Package myclass.graphics; This statement specifies that files in this package are stored under directory Path / MyClass / Graphics. The root directory of the package level is determined by the environment variable classpath.
In order to be able to use the classes already provided in Java, we need to introduce the required classes with the import statement. Import package1 [.package2 ...]. (ClassName | *); for example: import myclass.graphics. *; import java.io. *;
Compilation and Generating Pack If you have defined packet P1 in program Test.java, you are compiled as follows: Javac -d DestPath Test.java, the compiler will automatically establish a subdirectory P1 in the DestPath directory and will be generated. Class files are placed under DestPath / P1. Destpath can be one of the environment variables ClassPath.
5, the construction method of the object is a special method. Each class in Java has a constructor to initialize a new object of the class. The constructor has the same name as the class name, and does not return any data type. The system will be automatically executed when an object is generated. The content should be included in the constructor: § Define some initial value or memory configuration; § A class can have multiple construct methods (overload), which is executed according to the different parameters; § If the configuration method is defined in the program, Using an instance is a default constructor, it is a blanks that have no content. Public class Employee {Private String name; private int sales; public Employee (String n, int s) {name = n; salary = s;} public Employee (String n) {this (n, 0);} public employee () {This ("unknown");}} This object refers to your object, and its main role is to use this object as a parameter to transmit a method in other objects.
Class thisclass {public static void main () {bank = new bank (); bank.someMethod (this);}} Class Circle {Int r; Circle (int R) {this.r = r;} public area () {RETURN R * R * 3.14;}} SUPERSUPER refers to the parent class of this object. SUPER can be used to reference (covered) methods in the parent class, (hidden) variables and constructors.
Public class apple (int Price) {super (price); super.var = value; super.method;}}} The above program represents the use of the parent class to generate an instance, the Super must be a subclass The first statement of the constructor.
Finalizer When collecting garbage collection, the Java runtime system automatically invokes the Finalize () method of the object to release system resources. This method must be declared as follows: protected void finalize () throws throwable {...} finalize () method is implemented in the user-defined class, it can be covered in the user-defined class, but generally Finally, you want to call the Finalize () method of the parent class to clear all the resources used by the object. Protected void finalize () throws throwable {... // Release the resources used in this class Super.Finalize ();