Java object-oriented

Source: Internet
Author: User
Tags class definition instance method

the Java Language fully supports object-oriented inheritance, encapsulation, polymorphism, and purely object-oriented programming languages. Java is object-centric, and the entire program consists of a class (the smallest program unit in java). Java is a static language, and when a class is defined, the methods and properties of the class and its objects are fixed as long as they are not recompiled. Java introduces the mechanism of the package, which provides a class of multi-level namespaces for resolving class naming conflicts and class file Management. Once the package PackageName is used in the source file, it means that all the classes in the source file belong to the packet, and the full class name is the package name + class Name. The Java package mechanism requires that the package name in the source file also require the class file to be placed under the corresponding path. Classes of the same package are freely accessible, and different packages need to be prefixed, even if the parent-child package, for example: xxx.xxx.Test test = new Xxx.xxx.Test test (); To resolve this issue, the Import keyword was introduced for importing a class or all classes under the specified package hierarchy of import Package.subpackage ... classname/*, sometimes two packages have the same class name, and then you need to use the full path to specify which package name of this class. After JDK1.5 you can also use the import static package subpackage ... classname.filedname/* to import one or all of the static properties of a class.

Inheritance is an important means of object-oriented software reuse, and subclasses have the properties and methods of the parent class as a special kind of parent class; Java is a single-inheritance language (that is, There can be only one direct parent), because multiple inheritance can cause confusion in the inheritance structure, which is difficult for the program to Understand. Encapsulation refers to the Object's properties and details are hidden, not allow external direct access, exposed to the outside through public methods, let the method to manipulate or access these properties, so as to hide the details of the class, the implementation of logical control within the method, restricting unreasonable access to the property, data inspection can be done to ensure the integrity of the object information, Easy to modify, improve the maintainability of the code; the multi-state refers to the subclass object can be assigned to the parent class variable, but the runtime still dynamically shows the behavior characteristics of the SUBCLASS. class, object is an instance of class, object has the basic characteristics of identity uniqueness, classification, polymorphism, encapsulation, Good module independence, and the encapsulation of class improves the cohesion of class and reduces the coupling between objects. Messages are passed between an instance of a class and an instance of another class, enabling interaction between Objects.

Abstraction is the abstraction of the functional requirements of a software system into the data and behavioral characteristics we want to use.

The difference between object-based and object-oriented is that the object is only encapsulated, not inherited and polymorphic, such as Js.

In the Java language, everything is an object (except for 8 basic data types), We access it by reference, and the object is unique, each object has a unique identity to reference it, and if it loses its identity, the GC Recycles.

Structural relationships between        Classes: 1. general-special structure: also known as the classification structure is the inheritance, expressed as "is a" relationship, java through extands implementation, The process of abstracting a common parent class from a plurality of subclasses in an inheritance relationship, extracting from the whole class the process of infiltrating a class in an inheritance relationship is the process of deriving subclasses from the parent class, similar to the process of combining a class object into a whole class in a combinatorial relationship 2. The Whole-part structure: also known as the assembly structure is a combination of Has a "relationship, Java is implemented by saving a reference to another object in one class. If the existing class is modified to obtain a special version that the abstract class can change to a class that is appropriate for a particular requirement, inherit. such as animals and wolves. If there is a definite part-to-whole relationship between the classes, such as the person and the hand, then the application of the combination, the hand as the embedding property of the human hand to achieve the method of Human.

The

       class is a reference data type that can contain only properties, methods, constructors, initialization blocks, inner classes (including enumerations and interfaces) of 5 members, and classes are typically defined as Follows: [modifier] class Class name {0 to multiple constructor definitions: 0 to multiple properties ... 0 to multiple methods ...} Modifiers can be public, final, or completely omitted, with the first letter of the class name Capitalized. The format syntax for defining Attributes: [modifier] Property Type property name [= default] modifier is generally public, private, protected, static, final, and so On. The first letter of the property name is Lowercase. Defines the syntax of a method: the [modifier] method returns a method body of the value type method name (parameter List) {0 to multiple statements}, the modifier can be public, private, protected, static, final, abstract. Static-decorated methods can only access static members, because they belong to the class method, not to the instance members and methods that are decorated (for reasons see ①). The syntax of the constructor is defined as Follows: [modifier] constructor name (parameter List) {0 to multiple statements the method body} modifier can be public, protected, private one of them, can also be omitted, but does not allow the modifier is static, the name must be the same as the class name, The return value of the constructor is Implicit. The system-provided constructor is not a parameter, and when we define a constructor ourselves, the default constructor is not Provided. When you construct an object using new, the content stored in the heap and stack is the same as C and needs to be studied carefully. When objects are not used by any reference, the garbage collector reclaims them, and the same reference variables are set to null, as in c/e + +, by cutting off the reference relationship and waiting for GC Reclamation. The first letter of the member variable and local variable is named lowercase and the remaining words are Capitalized.

The parameter passing mechanism of Java is Value passing, which is the passing of a copy of the actual parameter, and the parameter itself is not Affected. The parameter variable method defines the following public void Test (int a, int b, String ... persons) his definition and public void test (int a, int b, string[] PERSONS) have the same effect, but call two , a Variable-parameter method can pass in an array or pass in multiple string values, while the latter can only pass an array, and a method that defines a variable can have only one variable parameter and is at the end of the method parameter List.

Variables include member variables (instance properties and class properties of static Adornments) and local variables (formal parameters, method local variables, code block local variables), The scope of the Class's properties for the same life cycle, the scope of instance properties, and the Instance. A member variable is defined without initialization, but the local variable definition needs to be initialized (except for formal parameters, because the system has completed initialization when the method is called). If the local variable and member variable in the method have the same name, the member variable can be accessed using this or the class Name. The class is initialized at the first use, when the class member variable allocates memory and initializes it in the heap, and the member variable is initialized at the first new instance and the storage area is different from the class member Variable. A local variable allocates memory space only after initialization and is on the STACK.

Access Control character; private->default->protected->public, detailed full-complement map

Constructor-style Java an important way to create objects ⑦ (even If you create objects in the form of factory mode, reflection, and so on, the substance remains the constructor), Java provides at least one constructor (the constructor supports Overloading) and frequently customizes the initialization operations in the Constructor. Because the constructor is primarily used by other method calls to return instances of the class, it is common to set the constructor to public, allowing other classes in the system to create the class object, which may be set to protected (subclass invocation), private (no Other classes are allowed to be created).

The syntax for inheritance (extension) is as follows: the Modifier class subclass extends Superclass{//class definition Part}java subclasses cannot inherit the constructor of the parent class. Extension and derivation are opposites of the same concept, and if no display is specified, the immediate parent class of the class is java.lang.Object, or the indirect parent class. Inheritance is reusable, but it destroys the encapsulation of the parent class and results in coupling, and the combination implements class reuse and a better encapsulation. Combinations can also be implemented for the purpose of class Taking. The private parent class object is typically defined in the class that originally was the subclass and is initialized in the constructor to assign a value to this private object, while implementing the method ⑩ of the original parent class.

polymorphic, There are two types of reference in java, one is the Compile-time type, one is the type of the runtime, and the other is the type of the object that declares the variable and the type of the variable that is assigned to it when it is actually run, or polymorphic if the type at compile time and the runtime are Inconsistent. Java allows a subclass object to be assigned to a parent class reference variable without any type conversion, known as the system Auto-complete transformation, because the baseclass baseclass = new Subclass () is present, and BaseClass behaves differently at run time, note, however, that if you call a method that is not in the parent class and that is not in the subclass, the runtime does exist, but it does not pass at compile time (you can type ⑨ by forcing the type into a subclass). however, Unlike properties and methods, properties that are not polymorphic are accesses to Compile-time properties, in which two objects are actually created (parent and subclass objects).

The initialization block is a fourth member of Java except for properties, methods, and constructors, and there can be more than one initialization block inside a class. It can also initialize Java objects with the following syntax: [static]{//any executable code} The order of initialization is the initial value specified when the initialization block or declared property is first executed, and finally the constructor is Initialized. Initialization is generally used to set the same initial value for all objects, thereby improving the maintainability of the code, the class initialization block is static decorated before the object initialization, he can not initialize the instance properties, the same as the constructor will be back to the same, class initialization stage, first to perform the top-level parent class static initialization block , down, down, only once, and then object initialization, first executing the initialization block of the topmost parent class, the constructor, and then Descending. The first time the JVM uses a class, the prep phase allocates memory for all static properties, which is the initial value specified when the static initialization block and class properties are Executed.

The essential reason that the ①static method can only access static members is that the This keyword is used in the static method and the appropriate this object cannot be found, so static cannot use the This reference and cannot use non-static members and METHODS. This is hidden by default when one method in a class calls another method, and when static methods and properties are called, the class is hidden by Default. Note the use and scope of this Object. Static methods and properties are owned by the class and the instance, so the class and instance (even if the instance is defined as null, but if the invocation is an instance method and the property is reported Nullpointerexception) can be called and the execution result is the Same. Normal methods and properties can only be called with instance objects and the result may vary depending on the object. When Java creates a class object, it implicitly creates the parent class object of the class, using super to point to the parent class object, and this is pointing to the object that called the method (the subclass object), which is the parent object to which this is pointing to the Object. So super cannot appear in static class methods (no matching parent is Found)

② recursion to the known direction

     ③ Overloads: The method is the same, the parameter list is different (the reason the return value of the method cannot be used to differentiate the overload is because the call might take the case where F () does not require a return value, and the system is not recognized at this time). If the formal parameter list is a mutable parameter, it may be necessary to pass in A.test (new string[] ("") to differentiate the use of single strings, as Appropriate. Overrides are subclasses that override the parent class, follow the "two same two small one rule" that is, the method name is the same, the parameter list is the same, the return value type of the two pinky subclasses method is smaller or equal than the return value type of the parent class method, and the exception that is thrown by the subclass method Declaration. The access rights of a Osashi subclass method should be greater or equal than the parent class. Overrides require the same class method or instance method, and you can use super to invoke the overridden instance method, using the parent class Name. Method calls the overridden class method in the parent class. If the parent class method is private, it cannot be overridden and inaccessible. Subclasses can overload methods of the parent class. Property Overrides: when a child class and a parent class have properties with the same name, the properties of the parent class can be accessed through super, and the class properties are accessed directly from the class Name.

④ Design Principles: 1. The benefit of using local variables is to reduce the lifetime of the variable and decrease the Overhead. Shorten the scope of variables, improve the cohesion of the Program. 2. The purpose of encapsulation: a class is often a small module, we should only let this module to expose what the outside world needs to know, hide some other content, so as to avoid the direct operation and access to another module in a module of data, the design of the module to pursue high cohesion (as far as possible, the Module's internal data, The feature implementation details are hidden within the module independently, without the external direct intervention being allowed, and low coupling (exposing only a small amount of methods to the outside world). 3. Most of the attributes in a class should be private, and some static-modified properties that are similar to global variables are considered using the public modifier. Some of the tools used to implement this class should also be defined as Private. if the methods inside the parent class only want the quilt class to be overridden, rather than being called directly outside, you should use protected to decorate the METHODS. Methods that you want to expose to other classes of free invocation should use public adornments, such as constructors, so that most of the parent class (top Class) is defined as public, because in most cases you want to be used by other free Classes. 3. The design principle of the parent class: as far as possible to hide the internal data of the parent, the property is set to private, do not let the subclass directly access, do not let subclasses arbitrarily access, modify (overwrite is Overridden) the method of the parent class, helper other methods in the parent class to apply the private adornment, the method needs to be modified with public , but you do not want the quilt class to be rewritten using the final Decoration. If the parent class wants a method quilt class to be overridden, but does not want to be freely accessible by other classes, you can use protected to decorate the method, and do not call the method overridden by the quilt class in the parent class constructor (a null pointer error is thrown). If you want to set a class as the final class (that is, you cannot be a parent), you can use the final decoration for this class. This is true of the java.lang.String and system in the jdk, or the constructor of the parent class is decorated with private, so that the class cannot invoke the constructor of the parent class and cannot inherit. You can now provide a static method to create an instance of the class. When to use Inheritance: subclasses add additional attributes, not just changes to the parent property values, and subclasses need to increase their own unique behavior (including adding new methods or overriding methods of the parent class).

⑤ variables that describe the inherent information of a class or object should be defined as member Variables.

⑥java Common Package: Java.lang contains the Java language core class string, System, Math, thread, etc., Java imports the default java.lang, so the use of String,system is not an Error. Java.util contains a large number of Java tool classes/interfaces and collection framework classes/interfaces, such as arrays and list, set, and so On. The java.net contains some Java network programming related Classes/interfaces. The java.io contains classes/interfaces related to Input/output programming. The java.text contains the Java formatting-related classes. java.sql contains java-related classes/interfaces for JDBC database programming. java.awt contains a class/interface for the abstract serial toolset, which is mainly used to build graphical user Interfaces. The java.swing contains classes/interfaces related to swing graphical user interface programming, which can be used to build platform-independent GUI Programs.

Whether the ⑦ constructor is entirely responsible for creating Java Objects: no, The system has allocated memory space for the object before invoking the constructor, and the default initialization, but still cannot be called externally, can only refer to it through the this pointer in the constructor, when the constructor execution ends, This object is returned as the constructor return value, It is also usually paid to another reference variable to access the object Externally. It is also generally recommended that if you customize a parametric constructor, the extra best to write provides a parameterless Constructor. Using this to call another overloaded constructor can only be used in the constructor, and must be placed in the first sentence of the Constructor's execution body. The constructor of the subclass calling the parent class is implemented using super and must be on the first row, so this and super do not appear at the same time. Regardless of the initialization code that calls the parent class constructor without super, the subclass invokes the parent class constructor before its constructor is Initialized. And it goes back to Java.lang.Object.

⑧ accesses a property in a method, in the order of a local variable in the method, to find the current class if there is this attribute (variable), to find the parent class, which is traced to Object.

⑨ Basic types of data type conversions can only be performed between numeric values, that is, integer, character, float, but not data-type conversions from Boolean. A reference type can only convert a parent class variable to a subclass type and satisfy this instance when it compiles as a parent class object, and the runtime is a subclass object, otherwise a classcastexception exception will occur, such as double d = 3.14; Long a = (long) d; Object obj = "hello" string objstr = (string) Obj;object objpri = new Integer (5) string str = (string) Objpri exception; to make the code more robust, you can use the If (obj instanceof string) {string str = (string) objpri}

⑩ using a composite relationship because the new parent class is required and passed into the constructor of the subclass to initialize the parent class object in the subclass will incur extra overhead, because the subclass also defaults to creating the parent class when the inheritance relationship occurs, but it is the Programmer's display to manually create the embedded class object, so there is no extra overhead.

Java object-oriented

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.