"Thinking before Class" 1. What is an object? What is a class? What is a package? What is an interface? What is an internal class? 2. What are the three properties of object-oriented programming? What are the characteristics of each of them? 3. Do you know what are the unique features of the Java language in object-oriented programming?
Difficulties: 1. Understand the method overloads and method overrides, and do not confuse the use of both. 2. class variables and the use of class methods. 3. The use of the interface. 3. 1 Object-oriented technology Foundation http://hovertree.com/menu/java/
3. 1. 1 basic object-oriented concepts The basic idea of object-oriented Object-oriented is an emerging program design method, or a new program design specification (paradigm), its basic idea is to use object, class, inheritance, encapsulation, message and other basic concepts to design. The software system is constructed from the objective object in the real world, and the natural way of thinking is used as much as possible in the system construction. The development of a software is to address some of the issues involved in the business scope called the software's problem domain. Its application areas are not only software, but also computer architecture and artificial intelligence.
1. Basic concepts of objects object is an entity used to describe objective things in the system, which is a basic unit of the system. An object consists of a set of properties and a set of services that operate on that set of properties.
A proactive object is a set of properties and a package of services, where at least one service does not need to receive messages to be actively executed (called an active service). 2. Basic concepts of classes A class is a collection of sets of objects with the same properties and services, providing a uniform abstract description of all objects that belong to the class, including properties and two main parts of the service. In an object-oriented programming language, a class is a stand-alone program unit that should have a class name and consist of two main parts: a property description and a service description.
3. News
A message is a service request to an object that should contain information such as the object ID of the service, the service identity, the input information, and the answer information. Services are often referred to as methods or functions.
3. 1. 2 basic object-oriented features
1. Encapsulation of Encapsulation is the combination of the object's properties and services into a separate unit, and as far as possible the inner details of the object, containing two meanings: ◇ Combine all the attributes of an object with all services to form an indivisible independent unit (i.e. object). ◇ Information concealment, that is, as far as possible to conceal the internal details of the object, the external formation of a boundary (or form a barrier), only the limited external interface to make it contact with the outside. The principle of encapsulation in the software reflects that the requirements of the object beyond the arbitrary access to the object's internal data (attributes), thereby effectively avoiding the external error on its "cross-infection", so that software errors can be localized, greatly reducing the difficulty of error-checking and debugging.
2. Inheritance of An object of a special class has all the properties and services of its generic class, called the inheritance of a special class to a generic class.
A class can be a special class of more than one generic class that inherits properties and services from multiple generic classes, called multiple inheritance.
In the Java language, we typically call the generic class the parent class (superclass, superclass), and the special class as a subclass (subclass).
3. Polymorphism The polymorphism of an object is that after a property or service defined in a generic class is inherited by a special class, it can have different data types or behave differently. This makes the same property or service have different semantics in the generic class and in each of its special classes. For example, the drawing method for geometry, ellipse and polygon are subclasses of geometry, and the drawing method functions differently. 3. 1. 3 Object-Oriented programming method Object-oriented analysis of ooa-object oriented analyses Object-oriented design of ood-object oriented Ooi-object oriented implementation object-oriented implementation 3. 2 Object-oriented features of the Java language
3. 2. Class 1 Class is an important compound data type in Java and is the basic element for composing Java programs. It encapsulates the state and method of a class of objects, which is the prototype of this class of objects. The implementation of a class consists of two parts: class declaration and class body
1. class declaration: [Public] [Abstract|final] class ClassName [extends Superclassname] [implements Interfacenamelist] {......} Where the modifier public,abstract,final describes the class's properties, classname the class name, superclassname the name of the class's parent class, and interfacenamelist the list of interfaces that the class implements. 2. Class Body The class body 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. Member variables Member variables are declared in the following way: [Public | protected | private] [Static] [Final] [Transient] [Volatile] Type VariableName; Member variables which Static variables (class variables), relative to instance variables Final: constant Transient: Transient variable for object archiving, for serialization of objects, see serialization of Objects Section Volatile: Contribution variable, for concurrent thread sharing 4. Member Methods The implementation of a method consists of two parts: a method declaration and a method body. [Public | protected | private] [Static] [Final | abstract] [Native] [Synchronized] ReturnType methodName ([paramlist]) [Throws ExceptionList]//method declaration {Statements}//Method body The meaning of a qualifier in a method declaration: Static: Class method, which can be called directly from the class name Abstract: Abstraction method, no method body Final: Method cannot be overridden Native: Integrating code in other languages Synchronized: Controlling access to multiple concurrent threads ◇ Method declaration Method declarations include method names, return types, and external parameters. The type of the parameter can be a simple data type, or it can be a composite data type (also known as a reference data type). For simple data types, Java implements value passing, the method receives the value of the parameter, but cannot change the value of these parameters. If you want to change the value of a parameter, use a reference data type, because the reference data type is passed to the method by the address of the data in memory, and the operation of the data in the method can change the value of the data. Example 3-1 illustrates the difference between a simple data type and a 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 Value after Change is:" +val); /* Value parameter Values are modified without affecting the value of the value parameter */ pt.ptvalue=101f; System.out.println ("Original Ptvalue is:" +pt.ptvalue); Pt.changeobjvalue (PT); Parameters for reference types System.out.println ("Ptvalue after changes is:" +pt.ptvalue);/* Reference parameter value modification, change the value of the reference parameter */ } public void Changeint (int value) { value=55; The value parameter has been modified inside the method } public void Changeobjvalue (passtest ref) { ref.ptvalue=99f; The reference parameter was modified inside the method } }
◇ Method Body The method body is the implementation of the method, which includes the declaration of the local variable and all legitimate Java directives. The scope of the local variable declared in the method body is inside the method. If the local variable has the same name as the member variable of the class, the member variable of the class is hidden. In order to distinguish between parameters and member variables of a class, we must use this. This-----refers to the current object in a method whose value is the object that called the method. The return value must be identical to the return type, or exactly the same, or its subclasses. When the return type is an interface, the return value must implement the interface. 5. Method overloading Method overloading means that multiple methods have the same name, but the parameters of these methods must be different, or the number of arguments is different, or the parameter types are different. The return type cannot be used to differentiate between overloaded methods. The sensitivity of the parameter types must be sufficient, such as parameters that cannot be of the same simple type, such as int and long. The compiler determines which method is currently used, based on the number and type of parameters.
6. Construction method ◇ The construction method is a special method. Each class in Java has a constructor method that initializes an object of the class. ◇ The construction method has the same name as the class name and does not return any data types. ◇ overloading is often used to construct methods. ◇ Construction method can only be called by the new operator
3. 2. 2 objects Class instantiation generates an object that is communicated by the object for interaction. Message passing activates the method of the specified object to change its state or to cause it to behave in a certain way. The life cycle of an object consists of three phases: build, use, and eliminate.
Cleanup of objects When there is no reference to an object, the object becomes a useless object. The Java garbage collector automatically scans the dynamic memory area of an object, collecting non-referenced objects as garbage and releasing them. System.GC (); System.exit ();//terminate the current JVM When system memory is exhausted or a call to System.GC () requires garbage collection, the garbage collection thread runs synchronously with the system. 3. 2. 3 Object-oriented features There are three typical object-oriented features in the Java language: encapsulation, inheritance, and polymorphism.
1. Encapsulation of In the Java language, an object is an encapsulation of a set of variables and related methods, where variables indicate the state of an object, and the method indicates the behavior of the object. Through the encapsulation of objects, modularization and information hiding are realized. The information hiding of members in a class is implemented by applying certain access rights to the members of the class. Qualifiers in the ◇java class There are four different qualifiers in the Java language that provide four different access rights. 1) Private A member of a class that is limited to private and can only be accessed by the class itself. If the constructor method of a class is declared private, other classes cannot generate an instance of the class. 2) Default A member of a class that does not have any access permission is the default (default) Access state: friend, which can be accessed by the class itself and the classes in the same package. 3) protected A member of a class that is qualified as protected can be accessed by the class itself, its subclasses (including subclasses in the same package and different packages), and all other classes in the same package. 4) Public The members of the class that are qualified as public can be accessed by all classes. "Table 3-1" The scope comparison of qualifiers for classes in Java
The same class Same package Sub-classes of different packages Different packages not subclasses
Private *
Default * *
Protected * * *
Public * * * *
2. Inheritance of Code reuse is implemented through inheritance. All classes in Java are obtained by inheriting the Java.lang.Object class directly or indirectly. Inherited classes are called subclasses, and inherited classes are called parent classes. Subclasses cannot inherit member variables and methods in the parent class that have access rights private. Subclasses can override the parent class's methods and name member variables with the same name as the parent class. However, Java does not support multiple inheritance, which is the ability of a class to derive from multiple classes of superclass. ◇ the hiding of member variables and the rewriting of methods Subclasses can change the state and behavior of a parent class to its own state and behavior by hiding the member variables of the parent class and the methods of overriding the parent class. For example: Class superclass{ int x; ... void SetX () {x=0;} ... } Class Subclass extends Superclass{ int x; The variable x of the parent class is hidden ... void SetX () {//override method of Parent class SetX () x=5; } .... } Note: The overridden method in a subclass and the overridden method in the parent class are to have the same name, the same parameter table and the same return type, except that the function body is different. ◇super Java uses super to access the members of the parent class, and super is used to refer to the parent class of the current object. There are three ways to use Super: 1) Access member variables that are hidden by the parent class, such as: super.variable; 2) Call the overridden method 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 (); Calling the parent class's constructor method x=5; Super () The first sentence to put in the method System.out.println ("in subclass:x=" +x); } void DoSomething () { Super.dosomething (); Calling a 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. Polymorphism In the Java language, polymorphism is embodied in two aspects: the static polymorphism implemented by method overloading (compile-time polymorphism) and the dynamic polymorphism (run-time polymorphism) implemented by method overrides. 1) Compile-time polymorphism During the compilation phase, the compiler will statically determine which method to invoke, depending on the parameters, by which overloaded methods are called. 2) Run-time polymorphism Because subclasses inherit all of the properties of the parent class (except private), the subclass object can be used as a parent class object. In a program where the parent object is used, the subclass object can be used instead. An object can invoke a method of a subclass by referencing an instance of the child class. ◇ overriding method invocation principle: The Java Runtime system determines which method to invoke, based on the instance that invokes the method. An instance of a child class that is called by the runtime system to invoke a method of a subclass if the subclass overrides a method of the parent class, and if the subclass inherits the method of the parent class (not overridden), the runtime system invokes the method of the parent class. In Example 3-6, the parent class object A refers to an instance of a subclass, so the Java runtime invokes the CallMe method of subclass B.
"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 (); } } ◇ the principles to be followed when overriding the method: 1) The rewritten method cannot have more restrictive access rights than the overridden method (which can be the same). 2) The rewritten method cannot produce more exceptions than the overridden method. 4. Other ◇final keywords The final keyword can modify the class, the member variables of the class, and the member methods, but the final function is different. 1) Final modifier member variable: Final modified variable, it becomes a constant, for example Final type variableName; When a member variable is modified, it is defined with an initial value and cannot be modified at a later time, while modifying a local variable does not require it. 2) Final modified member method: Final decoration method, the method cannot be overridden by the quilt class Final ReturnType methodName (paramlist) { ... }
3) Final class: Final decorated class, the class cannot be inherited Final class finalclassname{ ... } ◇ instance members and class members You can declare class variables and class methods with the static keyword in the following format: static type Classvar; Static ReturnType Classmethod ({paramlist}) { ... } If you do not use the static keyword adornment when declaring, declare it as an instance variable and an instance method. 1) instance variables and class variables Instance variables for each object are allocated memory through which the instance variables are accessed, and the different instance variables are different. The class variable allocates memory only when the first object is generated, and all instance objects share the same class variable, and each instance object's change to the class variable affects other instance objects. Class variables can be accessed directly through the class name, without having to be an instance object, or accessing class variables through an instance object. 2) Example methods and class methods Instance methods can manipulate instance variables of the current object, or they can manipulate class variables, which are called by instance objects. But class methods cannot access instance variables, only class variables. A class method can be called directly by the class name or by an instance object. The this or Super keyword cannot be used in a class method. Example 3-7 is an example of instance members and class members. "Example 3-7" Class Member { static int classvar; int Instancevar; static void Setclassvar (int i) { Classvar=i; Instancevar=i; Class methods cannot access instance variables } static int Getclassvar () {return classvar;} void Setinstancevar (int i) {classvar=i;//instance methods 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 ()); M1.setinstancevar (11); M2.setinstancevar (22); System.out.println ("M1. Instancevar= "+m1.getinstancevar () + "m2. Instancevar= "+m2.getinstancevar ()); } } ◇ Class Java.lang.Object Class Java.lang.Object are at the root of the class hierarchy of the Java development environment, and all other classes inherit this class directly or indirectly. This class defines some of the most basic states and behaviors. Below, we introduce some common methods. Equals (): Compares whether two objects (references) are the same. GetClass (): Returns the representation of the class to which the object is run, thus obtaining the appropriate information. ToString (): The string representation that is used to return an object. Finalize (): Used to purge objects before garbage collection. Notify (), Notifyall (), Wait (): For synchronization in multithreaded processing.
3. 2. 4 abstract classes and interfaces
1. Abstract class In the Java language, when a class is decorated with the abstract keyword, this class is called an abstract class, which is called an abstract method when it is used to modify a method with the abstract keyword. The format is as follows: Abstract class abstractclass{...} Abstract ReturnType Abstractmethod ([paramlist])//Abstraction method Abstract classes must be inherited, and abstract methods must be overridden. Abstract methods simply declare, do not need to be implemented, abstract classes cannot be instantiated, abstract classes do not necessarily contain 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 be declared abstract. 2. Interface An interface is an abstract class that contains only the definitions of constants and methods, without the implementation of variables and methods, and whose methods are abstract methods. Its usefulness is reflected in the following areas: ◇ the same behavior of unrelated classes is implemented through interfaces, regardless of the relationships between these classes. ◇ Specify the methods that multiple classes need to implement through the interface. ◇ interface to understand the object's interface, without needing to know the object's corresponding class. 1) Definition of the interface The definition of an interface includes the interface declaration and the interface body. The format of the interface declaration is as follows: [Public] Interface Interfacename[extends Listofsuperinterface] {...} The extends clause is basically the same as the extends clause of the class declaration, except that an interface can have more than one parent interface, separated by commas, and a class can have only one parent class. Interface bodies include constant definitions and method definitions The constant definition format is: type Name=value; The constant is shared by multiple classes that implement the interface; Property with public, final, static. Only constants can be declared in an interface, and variables cannot be declared. Method Body Definition Format: (with public and abstract attributes, cannot be declared as protected) ReturnType methodName ([paramlist]);
Note: In an implementation class for an interface, the implemented interface method must be declared public because the method defined in the interface is public (the default). So its implementation must be declared public. Otherwise the compilation will not pass. 2) Implementation of the interface In the declaration of a class, the Implements clause is used to denote a class using an interface, the constants defined in the interface can be used in the class body, and all methods defined in the interface must be implemented. A class can implement multiple interfaces, separated by commas in the implements clause. 3) Use of the interface type Interface is used as a reference type. Any instance of a class that implements the interface can be stored in a variable of that interface type, through which the methods in the interfaces implemented by the class can be accessed. 3. 2. 5 Internal classes
1. Definition and use of internal classes: An inner class is a class that is nested within a class, can be a member of another class, can be defined inside a block of statements, and can be defined anonymously within an expression. The inner class has the following characteristics: ◇ generally used within the class or statement block that defines it, you must give the full name when referencing it externally. The name cannot be the same as the class name that contains it. ◇ You can use the static and instance member variables of the class that contains it, or you can use the local variables of the method in which it resides. ◇ can be defined as abstract. ◇ can be declared as private or protected. ◇ if declared as static, it becomes the top class and no more local variables can be used. ◇ If you want to declare any static member in the inner class, the inner class must be declared as 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 ("listeners example"); F.add ("North", New Label ("Click and drag the mouse"); Tf=new TextField (30); F.add ("South", TF); F.addmousemotionlistener (New Mousemotionhandler ());//http://hovertree.com/menu/java/ F.addmouselistener (New MouseEventHandler ()); F.setsize (300,300); F.setvisible (TRUE); }//Why Ask 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); } } }
Description: The Add method of the frame class is derived from its ancestor class container class, and the Addmousemotionlistener and Addmouselistener methods are derived from their ancestor class component. The parameters of the Addmouselistener method are MouseListener interfaces, and the Mouseadapter class is the class that implements the MouseListener interface. Visible graphical interface responses to external events are implemented by adding listener 2. The definition and use of anonymous classes: An anonymous class is a special inner class that contains a complete class definition inside an expression. By modifying the Go () section of example 6-7, we can see the usage of anonymous classes. public void Go () { F=new Frame ("listeners example"); F.add ("North", New Label ("Click and drag the mouse"); Tf=new TextField (30); F.add ("South", TF); F.addmousemotionlistener (New Mousemotionhandler () { /* Defines an anonymous class, the class name is not explicitly given, except that the class is Subclass of Class Mousemotionhandler */ public void mousedragged (MouseEvent e) { String s= "Mouse dragging:x=" +e.getx () + "Y = "+e.gety (); Tf.settext (s); } }); F.addmouselistener (New MouseEventHandler ()); F.setsize (300,300); F.setvisible (TRUE); } 3. Advantages and disadvantages of the inner class: ◇ Advantages: Save the size of the bytecode file generated after compilation ◇ Disadvantages: Make the program structure unclear
Exercises:
1: Styling can not be from the parent class to the sub-class modeling, only from the subclass to the parent class. Otherwise compile can pass, error when executing
such as: Subclass SC = new subclass (); BaseClass BC = (baseclass) SC;---'s right.
and baseclass BC = new BaseClass (); Subclass SC = (subclass) BC;---is wrong.
BaseClass BC = new Subclass () is also correct, and the method body that executes when calling a method in BC is a method body of a subclass, but the method must exist at the same time in the subclass, in the parent class, if there is one in the subclass and not in the parent class, you cannot call Bc.submethod ();
If two classes are inherited from the same class (which must be directly inherited, otherwise not), then these two classes can be assigned values, such as: Panel and Frame inherit from container, so panel p = new Frame (), and Frame f = new Panel () are all correct |