Java object-oriented Features Summary, java object-oriented

Source: Internet
Author: User
Tags constant definition object serialization

Java object-oriented Features Summary, java object-oriented

 

Object-oriented features in Java
(Good summary)

[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 features of object-oriented programming? What are their respective features?
3. Do you know the unique characteristics of java in object-oriented programming?

Difficulties:
1. Understand method overloading and method rewriting. Do not confuse them.
2. Use of class variables and class methods.
3. Use of interfaces.
3.1 basic http://hovertree.com/menu/java/ of Object-Oriented Technology

3.1.1 basic object-oriented concepts
Basic Idea of object-oriented
Object-oriented is an emerging programming method, or a new program design specification (paradigm ), the basic idea is to use objects, classes, inheritance, encapsulation, messages and other basic concepts for program design. Construct a software system based on objective things (objects) in the real world, and use human natural thinking methods as much as possible in system construction. A software is developed to solve some problems. The business scope involved in these problems is called the problem domain of the software. Its application fields are not only software, but also computer architecture and artificial intelligence.

1. Basic concepts of Objects
An object is an entity used to describe objective things in a system. It is a basic unit of a system. An object consists of a group of attributes and a group of services that operate on these attributes.

An active object is a group of attributes and a group of service encapsulation bodies. At least one service can be actively executed (called an active service) without receiving messages ).
2. Basic concepts of Classes
A class is a set of objects with the same attributes and services. It provides a unified abstract description for all objects belonging to the class. The class includes attributes and services. In an object-oriented programming language, a class is an independent program unit. It should have a class name and contain two main parts: attribute description and service description.

3. Messages

A message is a service request sent to an object. It should contain the following information: the Object ID, service ID, input information, and answer information of the service. A service is usually called a method or function.

3.1.2 basic object-oriented features

1. Encapsulation
Encapsulation is to combine the attributes and services of an object into an independent unit, and conceal the internal details of the object as much as possible. It has two meanings:
◇ Combine all attributes of an object with all services to form an inseparable independent unit (that is, an object ).
◇ Information Hiding: to conceal the internal details of objects as much as possible, form a boundary (or form a barrier) externally, and retain only limited external interfaces to associate them with the outside.
The encapsulation principle is reflected in the software: the internal data (attributes) of the object cannot be freely accessed for parts other than the object ), this effectively avoids the "cross-infection" caused by external errors, so that software errors can be localized, greatly reducing the difficulty of error detection and troubleshooting.

2. Inheritance
Objects of special classes have all attributes and services of their general classes. They are called special classes that inherit general classes.

A class can be a special class of multiple general classes. It inherits attributes and services from multiple general classes. This is called multi-inheritance.

In java, we usually call a general class as a parent class (superclass, superclass), and a special class as a subclass (subclass ).

3. Polymorphism
Object polymorphism means that a property defined in a general class or a service that is inherited by a special class can have different data types or show different behaviors. This makes the same attribute or service have different semantics in the general class and its special classes. For example, the "plotting" method of "ry", "elliptic" and "polygon" are both subclasses of" ry". The "plotting" method has different functions.
3.1.3 Object-Oriented Programming Method
OOA-Object Oriented Analysis Object-Oriented Analysis
OOD-Object Oriented Design Object-Oriented Design
OOI-Object Oriented Implementation object-oriented Implementation
3.2 object-oriented features of Java

3.2.1 class
Class is an important composite data type in java and is the basic element of java program composition. It encapsulates the states and methods of a class of objects, and is the prototype of this class of objects. The implementation of a class includes two parts: class declaration and class body.

1. Class declaration:
[Public] [abstract | final] class className [extends superclassName] [implements interfaceNameList]
{......}
The modifiers public, abstract, and final indicate the class attributes. className indicates the class name, superclassName indicates the class parent class name, And interfaceNameList indicates the list of interfaces implemented by the class.
2. Class body
The class body is defined as follows:
Class className
{[Public | protected | private] [static]
[Final] [transient] [volatile] type
VariableName; // member variable
[Public | protected | private] [static]
[Final | abstract] [native] [synchronized]
ReturnType methodName ([paramList]) [throws exceptionList]
{Statements} // member Method
}
3. member variables
The declaration of member variables is as follows:
[Public | protected | private] [static]
[Final] [transient] [volatile] type
VariableName; // member variable
Where,
Static: static variable (class variable); relative to instance variable
Final: Constant
Transient: a temporary variable used for object archiving. It is used for Object serialization. For details, see the serialization section of objects.
Volatile: Contribution variable for concurrent thread sharing
4. Member Methods
Method implementation includes two parts: Method description and method body.
[Public | protected | private] [static]
[Final | abstract] [native] [synchronized]
ReturnType methodName ([paramList])
[Throws exceptionList] // method declaration
{Statements} // method body
Meanings of qualified words in method declaration:
Static: class method, which can be called directly by Class Name
Abstract: abstract method, no method body
Final: The method cannot be overwritten.
Native: code that integrates other languages
Synchronized: controls the access of multiple concurrent threads
◇ Method declaration
The method declaration includes the method name, return type, and external parameters. The parameter type can be either a simple data type or a composite data type (also called a reference data type ).
For simple data types, java implements value passing. Methods receive parameter values, but cannot change the values of these parameters. If you want to change the parameter value, you can use the reference data type because the referenced data type is passed to the address of the data in the memory. operations on the data in the method can change the value of the data.
Example 3-1 illustrates the difference between a simple data type and referenced 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
The modification of the value does not affect the value of the parameter */
Pt. ptValue = 101f;
System. out. println ("Original ptValue is:" + pt. ptValue );
Pt. changeObjValue (pt); // parameters of the reference type
System. out. println ("ptValue after Change is:" + pt. ptValue);/* modify the value of the referenced parameter by modifying the value of the referenced parameter */
}
Public void changeInt (int value ){
Value = 55; // The value parameter is modified inside the method.
}
Public void changeObjValue (PassTest ref ){
Ref. ptValue = 99f; // The reference parameter is modified inside the method.
}
}

◇ Method body
The method body is the implementation of the method. It includes the declaration of local variables and all valid Java commands. The scope of the local variables declared in the method body is within the method. If the local variables have the same name as the class member variables, the class member variables are hidden.
To distinguish between parameters and class member variables, we must use this. This ----- is used to reference the current object in a method. Its value is the object that calls this method. The return value must be the same as the return type, completely the same, or its subclass. When the return type is an interface, the return value must be implemented.
5. Method Overloading
Method overloading means that multiple methods have the same name, but the parameters of these methods must be different, the number of parameters is different, or the parameter type is different. The return type cannot be used to distinguish between overloaded methods.
The differentiation of parameter types must be sufficient. For example, a parameter of the same simple type, such as int and long, cannot be used. The compiler determines the current method based on the number and type of parameters.

6. Constructor
◇ Constructor is a special method. Every class in Java has a constructor to initialize an object of this class.
◇ The constructor has the same name as the class name and does not return any data type.
◇ Overloading is often used for constructor.
◇ Constructor can only be called by the new operator

3.2.2 object
Class instantiation can generate objects, and objects interact through message transmission. Message transmission activates the method of a specified object to change its status or make it produce certain behaviors. The lifecycle of an object consists of three stages: generation, use, and elimination.

Object clearing
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 the object and collects and releases the unreferenced object as the garbage collection.
System. gc (); System. exit (); // terminate the current JVM
When the System memory is used up or the System. gc () is called to request garbage collection, the garbage collection thread runs synchronously with the System.
3.2.3 object-oriented features
Java has three typical object-oriented features: encapsulation, inheritance, and polymorphism.

1. Encapsulation
In java, an object is the encapsulation of a group of variables and related methods. The variables indicate the state of the object, and the methods indicate the behavior of the object. Through object encapsulation, the module and Information Hiding are realized. By granting certain access permissions to the class members, the information of the members in the class is hidden.
◇ Restrictions in java classes
The java language has four different restrictions and provides four different access permissions.
1) private
Only private members can be accessed by the class itself.
If the constructor of a class is declared as private, other classes cannot generate an instance of the class.
2) default
Members without any access permission restriction in the class belong to the default access status: friend, which can be accessed by the class itself and the class in the same package.
3) protected
A member of a class limited to protected can be accessed by the class itself, its subclass (including the subclasses in the same package and in different packages), and all other classes in the same package.
4) public
Only public members can be accessed by all classes.
[Table 3-1] comparison of the scopes of class qualifiers in java


Same class
Same package
Subclass of different packages
Non-subclass of different packages

Private
*




Default
*
*



Protected
*
*
*


Public
*
*
*
*




2. Inheritance
Implement code reuse through inheritance. All classes in Java are obtained by directly or indirectly inheriting the java. lang. Object Class. The inherited class is called a subclass, And the inherited class is called a parent class. Subclass cannot inherit the member variables and methods whose access permission is private in the parent class. Subclass can override the parent class method and name the member variables with the same name as the parent class. However, Java does not support multi-inheritance, that is, the ability of a class to derive from multiple superclasses.
◇ Member variable hiding and method Rewriting
By hiding the member variables of the parent class and overwriting the parent class, subclass can change the status and behavior of the parent class to its own State and behavior.
For example:
Class SuperClass {
Int x ;...
Void setX () {x = 0 ;}...
}
Class SubClass extends SuperClass {
Int x; // hides the variable x of the parent class.
...
Void setX () {// override the setX () method of the parent class ()
X = 5 ;}....
}
Note: The method to be rewritten in the subclass and the method to be rewritten in the parent class must have the same name, the same parameter table and the same return type, but the function body is different.
◇ Super
In java, super is used to access the parent class members. super is used to reference the parent class of the current object. There are three scenarios for Super:
1) access hidden member variables of the parent class, such:
Super. variable;
2) Call the override method in the parent class, for example:
Super. Method ([paramlist]);
3) Call the constructor of the parent class, for example:
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 constructor of the parent class
X = 5; // The first sentence of super () in the method.
System. out. println ("in SubClass: x =" + x );
}
Void doSomething (){
Super. doSomething (); // 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. Polymorphism
In java, polymorphism is reflected in two aspects: static polymorphism implemented by method overloading (polymorphism at compile time) and dynamic polymorphism implemented by method rewriting (Runtime polymorphism ).
1) polymorphism during compilation
During the compilation phase, the compiler determines which method is called to be overloaded.
2) Runtime polymorphism
Because the subclass inherits all attributes of the parent class (except the private class), The subclass object can be used as the parent class object. Any place in the program that uses the parent class object can be replaced by a subclass object. An object can call the subclass method by referencing the subclass instance.
◇ Calling principle of the method Rewriting: The system determines which method to call based on the instance that calls the method during java runtime. For an instance of a subclass, if the subclass overrides the parent class method, the system calls the subclass method at runtime; if the subclass inherits the parent class method (not overwritten ), the system calls the method of the parent class at runtime.
In Example 3-6, parent class object a references a subclass instance. Therefore, the callme method of subclass B is called during java runtime.

[Example 3-6]
Import java. io .*;
Class {
Void callme (){
System. out. println ("Inside A's callme () method ");
}
}
Class B extends {
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 ();
}
}
◇ Principles to be followed during method Rewriting:
1) The rewritten method cannot have more strict access permissions (the same can be applied) than the rewritten method ).
2) The rewritten method cannot produce more exceptions than the write method.
4. Others
◇ Final keywords
Final keywords can modify the member variables and member methods of classes and classes, but they have different roles.
1) final modifier member variables:
Final modifies the variable to be a constant, for example
Final type variableName;
When modifying a member variable, the initial value is given during definition and cannot be modified later.
2) final member modification method:
Final modifier, this method cannot be overwritten by the quilt class
Final returnType methodName (paramList ){
...
}

3) final class:
The final modifier class cannot be inherited.
Final class finalClassName {
...
}
◇ Instance members and Class Members
You can use the static keyword to declare class variables and class methods. The format is as follows:
Static type classVar;
Static returnType classMethod ({paramlist }){
...
}
If you do not need to modify the static keyword during declaration, it is declared as an instance variable and an instance method.
1) instance variables and class variables
The instance variables of each object are allocated with memory and accessed through this object. Different instance variables are different.
Class variables are only allocated when the first object is generated. All instance objects share the same class variable. Changes to class variables of each instance object will affect other instance objects. Class variables can be directly accessed through the class name, without the need to form an instance object, you can also use the instance object class variables.
2) instance methods and class methods
The instance method can operate the instance variables of the current object, or the class variables. The instance method is called by the instance object.
However, class methods cannot access instance variables. They can only access class variables. Class methods can be called directly by class names or instance objects. This or super keywords cannot be used in class methods.
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; // The instance method can be either a category variable or an instance variable.
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 ());
}
}
◇ Java. lang. Object
Class java. lang. Object is at the root of the class hierarchy in the java development environment. All other classes inherit this class directly or indirectly. This class defines some of the most basic states and actions. Next, we will introduce some common methods.
Equals (): Compares whether two objects (references) are the same.
GetClass (): return the expression of the class corresponding to the object runtime to obtain the corresponding information.
ToString (): String Representation of the returned object.
Finalize (): Used to clear objects before garbage collection.
Y (), policyall (), wait (): used for synchronization in multi-thread processing.

3.2.4 abstract classes and interfaces

1. abstract class
In java, when an abstract keyword is used to modify a class, this class is called an abstract class. When an abstract keyword is used to modify a method, this method is called an abstract method. The format is as follows:
Abstract class abstractClass {...} // Abstract class
Abstract returnType abstractMethod ([paramlist]) // abstract Method
Abstract classes must be inherited and abstract methods must be overwritten. Abstract METHODS only need to be declared without implementation. abstract classes cannot be instantiated. abstract classes do not have to contain abstract methods. If the class contains abstract methods, 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 a type of abstract class that only contains the definition of constants and methods, without the implementation of variables and methods, and its methods are abstract methods. Its usefulness is embodied in the following aspects:
◇ Use interfaces to implement the same behavior of irrelevant classes without considering the relationships between these classes.
◇ Specify the methods to be implemented by multiple classes through the interface.
◇ Understand the interaction interface of objects through interfaces, without having to know the classes corresponding to objects.
1) Interface Definition
The interface definition includes the interface description and interface body.
The format of the interface declaration is as follows:
[Public] interface interfaceName [extends listOfSuperInterface] {… }
The extends clause and the extends clause declared by the class are basically the same. The difference is that an interface can have multiple parent interfaces separated by commas, and a class can only have one parent class.
The interface body includes constant definition and method definition.
The constant definition format is: type NAME = value. This constant is shared by multiple classes implementing this interface. It has public, final, and static attributes. Only constants can be declared in the interface.
The method body Definition Format is as follows: (it has public and abstract attributes and cannot be declared as protected)
ReturnType methodName ([paramlist]);

Note: In the interface implementation class, the implemented 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 the compilation will not pass.
2) interface implementation
In the class declaration, the implements clause is used to represent a class using an interface. In the class body, constants defined in the interface can be used, 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 the class implementing this interface can be stored in the variables of this interface type, and these variables can be used to invoke the methods in the interface implemented by the class.
3.2.5 internal class

1. Definitions and usage of internal classes:
An internal class is a nested class defined within a class. It can be a member of other classes, can be defined within a statement block, and can be anonymously defined within an expression.
Internal classes have the following features:
◇ It is generally used to define its class or statement block. A complete name must be provided when it is referenced externally. The name cannot be the same as the name of the class containing it.
◇ You can use static and instance member variables of the class containing it, or local variables of the method in which it is located.
◇ It can be defined as abstract.
◇ It can be declared as private or protected.
◇ If declared as static, it becomes the top-level class, and local variables cannot be used any more.
◇ To declare any static member in 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 ("Two 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 );
} // Question
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 class comes from the Container class of its ancestor class. The addMouseMotionListener and addMouseListener methods come from the Component class of its ancestor class. The parameter of addMouseListener is the MouseListener interface, the MouseAdapter class is a class that implements the MouseListener interface. The graphic interface responds to external events by adding listener.
2. Definitions and usage of anonymous classes:
An anonymous class is a special internal class that contains a complete class definition within an expression. By modifying the go () Statement in Example 6-7, we can see the usage of anonymous classes.
Public void go (){
F = new Frame ("Two 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, but the class is
Subclass of the MouseMotionHandler class */
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 internal classes:
◇ Advantages: saves the size of bytecode files generated after compilation
◇ Disadvantages: unclear program structure

Exercise:

1: The shape cannot be from the parent class to the Child class, but only from the Child class to the parent class. Otherwise, the code can pass during compilation and an error will be reported during execution.

For example: SubClass SC = new SubClass (); BaseClass bc = (BaseClass) SC; --- correct

BaseClass bc = new BaseClass (); SubClass SC = (SubClass) bc; --- it is incorrect.

BaseClass bc = new SubClass () is correct, and the method body executed when calling the method in bc is the method body of the SubClass, but the method must be in the SubClass at the same time, the parent class exists at the same time. If the child class exists but the parent class does not, bc cannot be called. subMethod ();

If both classes inherit from the same class (must be directly inherited, or not), the two classes can be assigned values to each other. For example, Panel and Frame inherit from Container, so Panel p = new Frame (); and Frame f = new Panel () are both correct.

Recommended: http://www.cnblogs.com/roucheng/p/3504465.html

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.