Summary of Java OOP and related fundamentals

Source: Internet
Author: User
Tags java se

Oop
    • There are three elements of the object
      • Behavior
        • What is the interface, what method/field can be used?
      • State
        • What happens to the object when the method is called?
        • The state of an object can be changed only by invoking a method
      • Identity
        • How do you differentiate between objects?
    • The three major relationships of the class
      • Dependence
        • Uses-a
        • Class used in the method (local variable of the method)
        • Should be as little as possible,
      • Aggregation
        • Has-a
        • own some kind of class (own field)
      • Inheritance
        • Is-a
        • General V.s. Specialized
Getting Started with Java self-brought classes
    • Only functionality's math is encapsulated.
    • Date
    • Gregoriancalander
Java OO Preliminary-taking date as an example
    • API documentation for Date
    • Date is used to denote a moment rather than a real-world moment (the design was intended to be UTC time, but did not comply with some complex calendar rules)
    • There are other classes that represent real-world time, such as Gregoriancalander (the usual Gregorian calendar), so that different locales can be used in different calendars, and they all inherit the calendar (as opposed to the too general date, A calendar plus a bunch of sub-classes is really a better design ... )
    • Derefernce a null will throw an error at runtime
    • All Java objects are placed on the heap
    • Like JS, Java objects are references, = only get shallow copy, require deep copy to call the object with the Clone ()
Java OO Preliminary-taking Gregoriancalander as an example
    • Api
    • Months from 0, in order to prevent errors and reduce reliance on the underlying implementation, the month is best to use the calendar of the virtual class constants, such as Calendar.december, the name of the week is the same
    • Get and set need to pass the relevant field through the arguments instead of calling different names directly, and the relevant field is represented by the Calendar's constant e.g. Deadline.set (Calendar.year, 2014)
    • Add can modify the time, and the increment of negative number indicates backwards
    • SetTime and gettime can be used to complete the conversion between Calander and date
    • There is a dateformatsymbols to get the name of the current locale about the date, such as what was called in Monday (Monday)? Monday (Chinese)? )
Custom Classes
    • The main function needs to be sent in a class
    • There can be only one public class in a file, and other classes may have multiple. The file name must be the same as the name of your public class
    • The Java compiler comes with a feature similar to make that will look for dependencies, if not found. Class will automatically find the corresponding. Java and compile it, or if. Java has been modified and will be recompiled
    • constructor is required and must be called with new, and will be used directly in the Compile times error
    • Although the variable declared in the method does not exist shadow, the name of the method parameter and the name of the class field can exist Shadow (the field that comes with this now needs to be prefixed with this), but the parameter name cannot be used to declare the new local variable
    • This and JS use the same, followed by Dot
    • The implementations of all classes in Java are written together with the declaration of the class, which is similar to the C + + inline declaration, except that in Java it is decided whether inline is the compiler's live
    • When you return a field of a class within a method, if it is an object, Java does not make a deep copy and then returns, so it actually returns a reference to the object , which destroys the encapsulation. The return value of the. Clone () that needs to be returned for this purpose
Static
  • The use of constants in Java class is also final declaration, and C + + is that it can be modified throughout the constructor (c + + constants must be set by member initializer This strange way, to the function body can not move), The constructor is not active.
  • The native functions in the Java standard library can bypass Java's own syntax limitations, such as a final field in an API that can be modified in some way (because native's functions are not implemented in Java (usually C/s ), so you can bypass this limitation)
  • Java's static method, like C + +, does not have this, cannot invoke a non-static method, and cannot use a non-static field. Similarly, the static method may not be called only with the class name, or it can be arbitrarily invoked with an object of this class, although this practice is relatively confusing, so it is not recommended
  • There are about two situations in which static is indicated for a method
    • This method does not change the state of the object, so there is no need to modify nonstatic filed
    • This method only needs to access the static field
  • The author spat out the triple meaning of the static name 2333 (C can refer to a variable that is initialized only once (most of the meaning of the static literal meaning), or only a variable that the current file can access. to C + + adds to the meaning of a common member in a class, which is the only thing Java has to follow.
  • In Java, where access is set up like C + +, the same class object can access each other's private members, and the subclass cannot access the private members of the parent class, but Java inherits only the public one, without the heap of complex rules
  • Incidentally introduced the Factory mode
  • The main function must also be static. Note that each class can have a main function, which makes it easy to do unit testing. At run time, only the main function in the. Class of the portal is used, and the main function of the other class is ignored. In this case, if you want to run a unit test of a class called ClassA, you can write a main function in this class and then execute

    $ Java ClassA

    If you want to run multiple classes, including the ClassA program, the entry is written in Runner.java, you can run

    $ Java Runner

    The main function of this classa is ignored. Note that it may also be necessary to add classpath instructions on how to find ClassA and other classes. In addition, the private class can have the main function, as long as the declaration is

    void Main (string[] args)

    On the line.

Parameters
    • Java and JS, everything is call-by-value, function parameters passed in the reference content can be changed, reference to the object cannot be changed, the original type is not a reference is direct copy and then sent in, how to move all right
The construction of the object
  • Java and C + + use signature to implement function overloading
  • All field will have a default initial value (number is 0, Boolean is false, object is null). Note that the field will have a default value, no initialization can be used, the local variable is not, not initialized can not be used.
  • As with C + +, a default constructor is provided when there is no constructor
  • Several convention of constructor parameter names used in Java to assign values directly to the field are
    • With first letter, lowercase
    • At the beginning plus a, hump
    • The direct same name, this time will produce shadow, so when the field is specified to add this
    • Without the underlined convention of C + +
  • Java constructors can actually call each other = Port = usage is

    This (...)

    The corresponding constructor is then matched according to the parameters passed in. This call must be written in the first sentence of the constructor. That way, if many constructors have the same code, they can be abstracted into one constructor, and then they are called together.

  • You can write the initial value directly to field in the class declaration, this initialization can be done before the constructor, so if some field requires a lot of constructors will give it the initial value, you can write in the class declaration, you do not have to write in the N constructor. Note that this initial value can also be the return value of a function, which does not necessarily need to be literal.
  • If the light with a function return value is not enough to initialize, then you can also use the initialization block, inside can write statements, see Initializing fields (the Java™tutorials > learning the Java Language > Classes and Objects)
  • Initialization block and field declarations are not necessarily sequential, can be mixed up, and no declaration of the field is still not initialized, here is a bunch of complex rules (complex to the early Java compiler itself some do not meet the speciation of the place) , it is generally advisable to write all the statements and then write initialization block.
  • The order of initialization is approximately
    1. Assign default values First
    2. field initializer and initialization block are executed in the order in which they appear in the code.
    3. If the constructor also calls another constructor (someone is going to write in the first line), call it
    4. The function body that finally executes this constructor
  • The static field can also be initialized with a static initialization block, just write the static in front of the curly braces.
  • The static initialization block will be executed at the first load of this class, so if you write a statement with the output Hello World in it, you can output Hello World without the main function: Although the runtime will make an error after executing the statement in the static initialization block, the main function is undefined. If you still want to escape this error, just add system.exit (0) just fine (this is really fun to play!!) )
Destruction of objects
    • There is no destructor in Java, but there can be a method called Finalize, which is executed each time the GC cleans up the object. However, the timing of the execution of this method is uncertain, so you cannot rely on it to reclaim resources. The best way is to recycle directly in any function that has applied for the resource.
    • Java's GC and JS are similar, with Mark and Sweep, so it's not possible to determine when finalize is called
Package
  • Java classes can be distributed in the package, and the naming of the package is usually written backwards in accordance with the domain name of the owning organization. So you will often see the pacakage called COM.XXX.YYY, the organization of the person who made the package is the domain name of the site will be xxx.com
  • Nested package does not contain a relationship, and the classes in Java.util and Java.util.jar are not the same.
  • A class that calls a package can indicate that it has a full name each time it is written, or import it to come in without having to write the name of the previous package. Import must be written at the beginning of the file.
  • Import can use * to get all classes of a package, and Eclipse provides the ability to expand * to the class name used in the file. Note * Can only be used to refer to all classes of a package, can not be placed on the previous level refers to multiple package
  • Bytecode all the class names are expanded, the difference between the Java compiler and the C + + compiler is that the C + + compiler does not look at the contents of the #inlcude file, and Java looks at the code of the Import class
  • Import can also be used to obtain the public static method of a class or field, when you need to write a statement like import static package.class.method (note import followed by static). If you want to import all static members, use * on the line.
  • If you want to add a new class to the existing package, you can write it before the declaration of this class.

    Package PackageName

    Plug the class into the specified package. If you do not write, this class will be put into the default package

  • The class compiled by the bytecode in the package needs to create a directory structure based on the package name (each point split element plus a layer of folders), placed in the project root directory. The JVM then knows where to find the bytecode of this class (assuming that the root directory is added to Classpath).
  • The package lookup is performed at run time, and the compiler does not check the JVM.
  • A class can reference other classes of the same package and other public classes of the package. Note that the class name is not written before the modifier default is private, but the field before the class is not written by default is public (as opposed to C + +). Many people forget to write private, so all classes in the same package can get the field freely, Java Standard Library of Java.awt.Window warningstring is such a field oh oh, and this bug has not been resolved (the author since the Black: we have in the core Java eighth version of the bug has been said that they have not changed, Obviously the maintainers of the Java standard library don't read our books. 2333)
  • For field with this kind of clerical error, you can secretly modify this field by setting the file directory + using the package, for example, using the bug in the standard library mentioned earlier, you can break through the encapsulation and modify the warningstring in the standard library 23333 but from the JDK 1.2 Start all Java. The package at the beginning is seal up and cannot be changed with the package.
Class path
  • The. Jar is also a zip format, so the software that opens the zip can also be used to open or unzip the. jar. It is usually a directory structure that is structured according to the name of the package, which is placed according to the rules. Class and other files, which saves space.
  • When the JVM looks for a class, it starts to look for the package by its name in the directory listed in class path. Class path can be set in the compiler instruction with-classpath (abbreviated-CP), or you can set a generic list in the environment variable Class_path.

    • Note that the default class path includes the working directory of the runtime when there is no-classpath in the run instruction. However, if there is a class path, the working directory will not appear in the default, there are two solutions

      1. Add a working directory directly to the class path, e.g. under the Unix-like system

        $ JAVA-CP.:d ir1:dir2:dir3:dir4  ... ClassName

        The starting point is the working directory, separated by a colon under the unix-like system (with a semicolon under win)

      2. Add that point directly to the environment variable class_path, so you don't have to set it up every time you write the build command.
    • Note that it is not a good thing to set an environment variable, and once the Class_path is indicated and not added to it, each time the class path is missing the current directory-Apple's QuickTime installer has done a good job
    • The compiler (JAVAC) always checks the current directory and does not check the runtime (Java)
    • Note that the wildcard usage in class path is different from Linux, * can not be arbitrarily used, see Java SE documentation:setting the class path
  • Files and jars in the runtime library are automatically added to the class path
  • The JVM 's lookup order is
    1. Search in the runtime library (e.g. Jre/lib)
    2. In the package nested in class path.
    3. Start looking from the current directory
    4. Find in the jar indicated in class path
  • Java compiler Lookup
    • The compiler will refer to all import statements to search
    • The compiler will start with each directory specified in class path and expand the import statement to search
    • The compiler found the updated code is also automatically recompiled
    • Compile-time errors are reported when multiple classes with duplicate names are found
    • Because a file can have only one public class, and the file name is the same as the class name, the compiler is much more convenient when looking for a file. But if a class in the same package can import other private classes of the same package, this is the time to rely on the compiler to look at the files in the bag.
    • So the Java compiler's lookup is less necessary to write a bunch of directories in class path, but much slower
Comments
    • Java has a very hanging tool called Javadoc, which is described here and here. As long as you write the comments in the agreed-upon way, you can automatically generate an HTML document by running with Javadoc. JDK6 's official API documentation and the official Hadoop API documentation are generated using this.
    • JDK6 generated style too much pain, his own demon changed a CSS here. Fortunately, the document generated by Javadoc will share a stylesheet.css in the directory, which can affect the appearance of this set of documents by modifying it.

Before

After

Some tips
    • When there are too many basic types of field in a class, it may be that some fields themselves can form a class and then add in.

Http://www.cnblogs.com/joyeecheung/p/3859430.html

Java OOP and related Fundamentals summary (GO)

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.