Java Object-oriented

Source: Internet
Author: User
Tags constant definition finally block instance method try catch log4j

Construction Method 1. The procedure used to describe the creation of an object, the construction method is called during the creation of the object 2. If the class does not have a write constructor, the system defaults to an argument-free constructor, and if a constructor is present in the class, the system does not provide the default parameterless constructor syntax: Access modifier constructor Method name () {// Initialize code}

Method overloading Principle: 1. Method name is the same 2. Parameter list is different 3. With return value, access modifier independent method overrides; Principle: 1. Method names are the same 2. The parameter list is the same 3. The return value type is the same or its subclass 4. Access rights cannot be strict with the parent class

The This keyword, which represents the current object, cannot be omitted in the argument constructor method

Benefits of Encapsulation: 1. To hide the implementation details of a Class 2. Data can only be accessed by the prescribed Method 3. Easy to join the control Statement 4. Easy to modify the implementation

Package steps: 1. Modify the visibility of a property 2. Create a Get,set Method 3. Add the attribute 4 to the Get,set method. Implementing the Get,set Method

Static keyword (Adornment: property, method, code block, inner Class) decorated property: A variable method that is shared with all instance objects of a class: belongs to a static method and can be directly called by the class name. Method Name () code block: Executes when the class is loaded, because the class is loaded once, so the static code block also Run only once, typically using a static block of code to load some statically-resourced

The difference between static and non-static modifiers is static, non-private decorated non-static,private modifier attribute Class property, class variable instance property, instance variable method class method, instance method class name. The property invokes the method class name. Method () object. Property object. Property Object. Method () A single object belonging to a class

Advantages of Inheritance: 1. Improve code reusability 2. Improve the maintainability of the code later

Use inheritance to write the parent class class pet{//Public properties and methods} Write subclass inherit parent class class extends pet{//subclass specific properties and methods}

Inherited steps: 1. Extract the properties and methods of multiple classes, and build a parent class 2. Use the extends keyword after the subclass to complete inheritance 3. You can call the code of the parent class in a subclass note: In Java, a single inheritance, only one parent after the extends keyword

Super Keyword (representing the parent class object) Super. Method Name 1. Only must appear in the method and constructor method of the subclass 2. Called in the constructor method and must be the first sentence 3. Private member of Parent Class 4. Access to members of the parent class

A member of a parent class member that cannot be inherited 1.private (1. You can modify properties and Method 2. This class, same package, subclass can be accessed) 2. Subclasses are not in the same package as the parent class, and members using the default access rights are 3. Construction method

Access modifier protected 1. Properties and Method 2 can be decorated. This class, the same package, the subclass can access

Access modifier: Private friendly protected public

Multiple inheritance relationships: Parent-class properties, Parent-class construction method, subclass property--Subclass construction method

Object initialization procedure 1. Before you create a class, check that the class is loaded, value the file of the parent class first, and then load the file of the Class 2. Allocates the space of the object, recursively assigns all the parent class and subclass the property Space 3. Assign a value of 4 to the property. Call the constructor of the parent class 5.

Abstract keyword 1. A modifier class that abstracts classes (-public abstract class name {}-abstract classes are used to represent some abstract concepts) the characteristics of abstract classes: 1. Abstract classes cannot be instantiated 2. Abstract classes can have attributes, methods, construction methods, are used to inherit the subclass 3 The methods in the abstract class are not necessarily all abstract methods 2. Method of modification, abstract method (-access modifier abstract return value type method name (parameter list);-abstract methods do not need to implement themselves, subclasses to implement) the characteristics of the abstract method: 1. Abstract methods have no method body 2. Abstract methods must appear in the Abstract Class 3. After a class inherits an abstract class, it must implement all of the abstract methods inside it 3. Abstract classes can inherit abstract classes

Final keyword (final) 1. Can be used to decorate classes, properties, Method 2. The decorated class cannot be inherited by 3. The modified method, can not be overridden by the Class 4. Modified variable, the value cannot be changed after initialization 5. A variable of a reference type that is modified, the reference address cannot be changed, But only the first layer is qualified, and the properties of the reference type can be changed.

The contrast abstract of abstract,final can be used to modify classes and methods, cannot be used to modify properties and construct methods final can be used to decorate classes, methods and properties, and cannot be decorated with construction methods

Polymorphic implementations (two elements: 1. Subclasses override the parent class Method 2. Using the parent class's type) 1. Write the parent Class 2. Write subclasses, subclasses override parent class Method 3. Runtime, using the parent class's type, object of the child class

Transformation of subclass to parent class (UP) transformation of parent class to subclass (downward transition)-a reference to a subclass that refers to a parent class reference to a child class object

Use two forms of polymorphism: 1. Use the parent action to implement Polymorphic 2 for the method parameter. Use parent class actions to implement polymorphism for the return value

The instanceof operator (used to determine whether an object belongs to a class or implements an interface) is commonly used in conjunction with coercion type conversions to improve the robustness of code syntax objects instanceof classes or interfaces

Polymorphism Benefits: Polymorphism can reduce the amount of code in a class, which can improve code extensibility and maintainability

interface syntax [modifier] Interface interface Name extends parent interface 1, parent interface 2, ... {//constant definition//method definition} Class class name extends parent class name Implement Interface 1, interface 2, ... {//class member}

Interface features: 1. Interfaces cannot be instantiated 2. The implementation class must implement all methods of the interface 3. The implementation class can implement multiple interfaces 4. The variables in the interface are static constants

Interface principle: 1. Can reduce the coupling between the code 2. Improved Code Extensibility and maintainability

Differences between interfaces and abstract classes: Abstract classes facilitate code reuse interfaces for code maintenance

interface keyword (c #) syntax [modifier] Interface Interface Name: Parent interface 1, parent interface 2, ... {attribute definition method definition} Class class name: Parent class Name, interface 1, interface 2, ... {}

Implements keywords one can implement multiple interfaces, using "." Between multiple interfaces. Separated

Interfaces have better features than abstract classes: 1. Can be inherited more than 2. Design and implementation complete separation 3. More natural use of polymorphic 4. Easier to build program framework 5. Easier to replace

Inner Class (There is also a class in the class that writes the class to class)-Maximum effect: encapsulation 1. Static inner classes use the static modifier, which declares that static members of the outer class can be accessed in a static inner class in the class body 2. The member inner class is declared in the class body without using static. Has the member characteristics of the class.  That is, you must have an instance of the class to create an inner class instance to which you can access the shared external class member variable 3. The local inner class declares the class in the method, which is the local inner class, and the scope is similar to the local variable 4. Anonymous inner Class (callback mode) anonymous classes can be written anywhere, like general statements  The syntax is more like creating an object: Date D=new date () {//...} An anonymous class is an inheritance of the original class, and an instance is created, and {} is the syntax for all classes that can be used in an inherited class body class. Anonymous class cannot write constructor anonymous classes can inherit from an abstract class or interface and must provide an implementation of an abstract method

Exception (Exception)-refers to an unhealthy event that occurs during a run in a program that interrupts a running program Errors (Error)

If-else Cons: 1. The code is bloated, adding a lot of exception case judgment and handling code 2. Reduce the time to write business code, inevitably affect the development efficiency 3. It's hard to get all the exceptions, the program is still not strong 4. The exception handling code and business code are intertwined, affecting the readability of the code. Increase the difficulty of maintenance of future procedures

if (In.hasnextint ()): Determines whether the input is of type int, or False if True is returned

Java exception handling is implemented by 5 keywords: try Catch finally throw throws try,catch,finally catch exception throws declare exception (declaring a method may throw various exceptions) throw exception

Catching exceptions using Try-catch blocks the first case: code snippet after normal try catch Try-catch block second case: Exception occurred try-------> Generate exception object into Catch block | Catch <----------exception type matching | The code snippet after the program continues Try-catch block the third case: Exception class does not match occurrence exception try-------> produce Exception Object | Catch Exception Type mismatch | Code snippet after program break run \ Try-catch block

Handling exceptions in Catch blocks join user-defined processing information System.err.println ("Custom Content"); Call method Output exception information E.printstacktrace () exception object Common method void Printstacktrace (): Output exception of the heap vertebral information string getMessage (): Returns the exception information description string, which is Printsta Cktrace () Part of the output information

Java exception mechanism 1. When the code runs to the code where the exception might occur, the exception object is thrown by the programmer or the JVM. The exception object logs information about the exception 2. After the exception object is thrown, it will look for the exception handling related code (catch), if found, the exception to this end 3. If not found, the exception object will continue to throw, looking for exception handling code 4. If the exception handling code is not found in main, The exception will be thrown to the virtual machine by main 5. Every layer of code thrown by an exception is interrupted

Common exception Types Exception the root class of the exception hierarchy Arithemticexception arithmetic error scenarios, such as zero divisor arrayindexoutofboundsexception array subscript out of bounds nullpointerexcept   Ion attempts to access a null object member ClassNotFoundException cannot load the required class inputmismatchexception the data type you want does not match the type that was actually entered IllegalArgumentException The ClassCastException method received an illegal parameter to force a type conversion error numberformatexception a numeric format conversion exception, such as converting "ABC" to a number

Try-catch-finally Try | There is an exception catch block System.exit (); Interrupt program, exit Java Virtual machine finally block

The try-catch-finally block with return has an exception try---1---> Generates an exception object into the Catch block |   catch<----2-----exception type Match return | |3 Execute finally block 4 |---> Execute return|        Exit Method |  |       | Finally

Try-catch-finally block usage rules try{//must appear and can only occur once}catch (Exception ex) {//can appear 0-n times,//If no cat CH, there must be finally}finally{//can appear 0-1 times}

Multiple catch blocks 1. Sort the order of the catch statements, first subclass stepfather Class 2. When an exception occurs, match each of the 3. Only the first catch statement that matches the exception type is executed exception try--------> produce Exception object    |    Catch and Exception type 1 do not match into catch block |      catch<-----------mismatch with exception type 2 |  |    Catch | The code snippet after the return try-catch-finally block

Exceptions in Java fall into two categories: 1. Run-time exception 2. Check for exceptions/detections

Custom Exception First step: Write an Exception class inheritance exception step two: Manually implement all the various methods of exception

Log category 1.SQL log 2. Exception Log 3. Business Log

Open Source Logging tool log4j control log output level control log information The destination is the console, and the file controls each log output format

Logging using log4j Step 1. Add log4j jar files to the Project 2. Create a log4j.properties file 3. Configure log information 4. Logging Information using log4j

Object in Java class inheritance structure Java.lang.Object class at the top if a Java class is defined without declaring its parent class with the extends keyword, its parent class defines an object for the Java.lang.Object class of object  The basic behavior of the quilt class default inherits public class foo{...} Equivalent to all objects public class Foo extends object{...}

The ToString method, which is used to return the character representation of an object (a string that can represent the contents of the object's properties), is defined in the. Object class, and all Java classes inherit the ToString method, and the string returned by the object class ToString method is: " Class name @hashcode value "Java class can override the ToString method to return more meaningful information as needed

The Equals method of the Equals object is used for the "equality" logic of the object, the logic of the Equals method is: If you think that the object calling the method (this) is equal to the Parameter object, returns True, otherwise false is called by the Equals method of the object class. The Equals method that inherits from object is returned only if this and obj are the same object True,java can be overridden as needed

Hashcode the default hashcode () value is an integer of the current heap object address translation, which is not a memory address generally uses the OID value of the object as the value of the Hashcode OID is the unique number of the object, in the project generally adopt the database generation OID, that is, the database " Primary Key "

Package Class (wrapper Class) wrapper class corresponding to the basic type Java.lang.Integer int Java.lang.Long Long java.lang.Double Double java.lang.Cha       Racter Char java.lang.Boolean Boolean java.lang.Byte Byte java.lang.Float Float java.lang.Short Short

The compiler supports "unpacking" the wrapper class: wrapping the basic type data encapsulated by the class object before the operation is "boxed": The result is encapsulated into a wrapper object after the operation

jdk5t added automatic "unboxing" and "boxing" function of the integer i=100; integer j=200; integer i+j; in fact, JDK5 's automatic "boxing" and "unboxing" is a compiler that relies on JDK5 "preprocessing" at compile time

Date (represents a specific instantaneous, accurate to milliseconds) class long (representing time, date)  gettime date-> millisecond difference for obtaining the corresponding millisecond difference  settime millisecond difference->date used to set the time by millisecond difference/ An argument-free construction method that constructs a date object that encapsulates the current date and time information  date date=new date (); SimpleDateFormat Class (conversion to implement date information for a Date object and string representation)   Common format strings      characters   meanings    examples        y     yyyy year-2017; YY-17 year       m          Month                MM-01 Month, M-1 month       d         Day                dd-06 Day, d-6 day        e        Week               E-Sunday (Sun)       a     am or PM logo            A-PM (PM)       h    hours (24 hours)        A-h-12 o'clock in the afternoon        h    hours (12 hours)        hh:mm:ss-12:46:33        m        min               hh (a): mm:ss-12 (PM): 47:48       s          seconds

Calendar and GregorianCalendar (used to encapsulate the information of calendars) The main function is that the method can calculate the time component

Calendar c=calendar.getlnstance (); The Getlnstance method will return the implementation of different Calendar classes based on the geographic information of the system

Getactualmaximum (can return a time component maximum) The Add method can add a value (decrease) to a date component

Interface Collection-list,set list:arraylist,linkedlist Set;hashset,treeset map:hashmap,treemap

Collections (Collection Tool Class)--provides a set of sorting, traversal and other algorithms to implement the collection interface

Java Object-oriented

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.