The creation and destruction of the objects of Java teaching notes _java

Source: Internet
Author: User

The goal of this course is to help you use Java more effectively. Some of the advanced topics are discussed, including object creation, concurrency, serialization, reflection, and other advanced features. This course will provide guidance on your Java-savvy journey.

1. Introduction

In the Tiobe programming language rankings, the Java language developed by Sun Company in 1995 is one of the most widely used programming languages in the world. As a general-purpose programming language, the Java language is attractive to software development engineers because of its powerful toolkit and runtime environment, simple syntax, rich platform support (one written, running everywhere), and unusually active community support.

In this series of articles, the high-level Java-related content is covered, so assume that the reader has a basic language knowledge. This is not a complete reference manual, but a detailed guide to your skills to a higher level.

This course contains a large number of snippets of code that, in contrast, provide examples of Java 7 and Java 8.

2. Instance Construction

As an object-oriented language, the creation of objects may be one of the most important concepts in the Java language. The construction method is of great importance in the initialization of an object instance, and Java provides several ways to define the construction method.

2.1 Implicit (generated) method of construction

Java allows you to define a class without declaring any construction methods, and this does not mean that the class does not have a construction method. Let's look at the definition of the following class:

Package com.javacodegeeks.advanced.construction;

public class Noconstructor {
}

This class does not define a constructor method, but the Java compiler implicitly generates one for it, allowing us to create a new object instance using the New keyword.

Final Noconstructor noconstructorinstance = new Noconstructor ();

2.2 Non-parametric construction method

The parameterless construction method is the simplest way to replace the Java compilation generation construction method with explicit declarations.

Package com.javacodegeeks.advanced.construction;

public class Noargconstructor {public
  noargconstructor () {
    //constructor body here
  }
}

The above constructor is invoked when a new object instance is created with the use new keyword.

2.3 Parametric Construction method

The parametric constructor method is most interesting and widely used to customize the creation of new instances by specifying parameters. The following example defines a construction method that has two parameters.

Package com.javacodegeeks.advanced.construction;

public class Constructorwitharguments {public
  constructorwitharguments (final string arg1,final string arg2) {
    //constructor body here
  }
}

In this scenario, when you use the New keyword to create an instance, you need to also provide two parameters defined on the constructor method.

Final constructorwitharguments constructorwitharguments = 
  new Constructorwitharguments ("Arg1", "arg2");

Interestingly, the constructor method can be invoked with each other through the This keyword. In practice, it is recommended that you use this to link multiple construction methods to reduce code duplication and to base the object on a single initialization entry. As an example, the following code defines a constructor method that has only one parameter.

Public constructorwitharguments (Final String arg1) {This
  (arg1, null);
}

2.4 Initializing blocks of code

In addition to constructing methods, Java also provides the logic to initialize the code block by initializing it. Although this usage is rare, it is no harm to know more about it.

Package com.javacodegeeks.advanced.construction;

public class Initializationblock {
    //initialization code here
  }
}

On the other hand, the initialization code block can also be considered as an implicit construction method without parameters. Multiple initialization blocks can be defined in a specific class, and are invoked at the time of execution in the order in which they are placed in the code, as shown in the following code:

Package com.javacodegeeks.advanced.construction;

public class Initializationblocks {
    //initialization code here
  }

  {
    //initialization code here< c7/>}

}

The real-starting code blocks are not meant to replace the construction method, but they can appear at the same time. Remember, however, that initialization code will be executed quickly before the method call is constructed.

Package com.javacodegeeks.advanced.construction;

public class Initializationblockandconstructor {
    //initialization code here
  }
  
  Public Initializationblockandconstructor () {
  }
}

2.5 guaranteed to construct default values

Java provides a determined initialization guarantee, and programmers can use initialization results directly. Uninitialized instances and class variables (static) are automatically initialized to the corresponding default values.

Type default value
Boolean False
BYTE 0
Short 0
int 0
Long 0L
Char \u0000
Float 0.0f
Double 0.0d
Object references null
Table 1

We use the following example to verify the default values in the previous table:

Package com.javacodegeeks.advanced.construction;
  public class Initializationwithdefaults {private Boolean booleanmember;
  Private byte Bytemember;
  Private short Shortmember;
  private int intmember;
  Private long Longmember;
  Private char Charmember;
  private float Floatmember;
  Private double doublemember;

  Private Object Referencemember;
    Public Initializationwithdefaults () {System.out.println ("Booleanmember =" + Booleanmember);
    System.out.println ("Bytemember =" + Bytemember);
    System.out.println ("Shortmember =" + Shortmember);
    System.out.println ("Intmember =" + Intmember);
    System.out.println ("Longmember =" + Longmember);
    System.out.println ("Charmember =" + Character.codepointat (new char[] {charmember}, 0));
    System.out.println ("Floatmember =" + Floatmember);
    System.out.println ("Doublemember =" + Doublemember);
  System.out.println ("Referencemember =" + Referencemember);

 }
}

After instantiating an object with the New keyword:

Final Initializationwithdefaults initializationwithdefaults = new Initializationwithdefaults (),
You can see the output from the console as follows:

Booleanmember = False
bytemember = 0
shortmember = 0
intmember = 0
longmember = 0
charmember = 0
F Loatmember = 0.0
doublemember = 0.0
Referencemember = null

2.6 Visibility

The construction method complies with the Java visibility rules and can determine whether the constructor method can be invoked in other classes through the access control modifier.

Modifier package Visible--class visibility public visibility
Public visible visible
Protected visible is invisible
< no modifiers > visible invisible
Private not visible invisible
Table 2

2.7 Garbage collection

Java (The JVM, to be exact) has an automatic garbage collection mechanism. In short, when new objects are created, they are automatically assigned to them, and when objects are no longer referenced, they are automatically destroyed and the corresponding memory is reclaimed.

Java garbage Collection uses the mechanism of generational recycling and is based on the assumption that "most objects are short-lived" (that is, they are not referenced soon after the object is created, so they can be destroyed safely). Most programmers habitually think that object creation in Java is inefficient, so try to avoid creating new objects as much as possible. In fact, this kind of understanding is wrong. The overhead of creating objects in Java is fairly low and fast. The real generation of huge overhead is unnecessarily long-lived objects, so they eventually migrate to the old age and cause Stop-the-world to occur.

2.8 Object Terminator (finalizers)

We talked about the topics that are related to constructing methods and object initialization, but have not yet mentioned their opposite: object destruction. The main reason is that Java uses the garbage collection mechanism to manage the lifecycle of objects, so destroying unnecessary objects and freeing the required memory is the responsibility of garbage collection.

However, Java provides another feature similar to the destructor's finalizer (finalizer), which is responsible for a variety of resource cleanup. Finalizer is generally seen as a dangerous thing (because it can cause many side effects and performance problems). Finalizer is not usually needed, so try to avoid it (except for very rare scenarios that contain a large number of local objects (native objects). The try-with-resources syntax and autocloseable interface introduced in Java 7 can be used as an alternative to finalizer and can be written in the following concise code:

Try (final inputstream in = Files.newinputstream (path)) {
  //code here
}

3. Static initialization

Above we learned about the construction and initialization of class instances, and in addition, Java supports class-level initialization constructs, called static initialization. Static initialization is similar to the initialization code block described above, with additional static keyword modifications. It is to be noted that static initialization is performed only once when the class is loaded. Examples are as follows:

Like the initialization code block, you can define multiple static initialization blocks in a class that determine the order in which they are executed when they are initialized. Shows for example under;

Package com.javacodegeeks.advanced.construction;

public class Staticinitializationblocks {
  static {
    //Static initialization code here
  }

  static {
    // Static initialization code here
  }
}

Because the static initialization block can be triggered by multiple threads executing in parallel (when the class is initially loaded), the JVM runtime guarantees that the initialized code is executed only once in a thread-safe manner.

4. Constructor mode

Many of the more comprehensible constructors (creator) Patterns of the years have been introduced into the Java community. Here are a few of the more popular: single case, helper class, factory, and dependency injection (also known as control reversal).

4.1 Single case mode

A single example is a long history but a controversial model in the software development community. The core idea of a single example pattern is to ensure that only one object is created at any given class. While it sounds simple, there is a lot of discussion about how to create objects in a correct and thread-safe way. The following code shows a simple version of the single example pattern implementation:

Package com.javacodegeeks.advanced.construction.patterns;

public class Naivesingleton {
  private static Naivesingleton instance;
  
  Private Naivesingleton () {    
  } public
  
  static Naivesingleton getinstance () {
    if (instance = = null) {
      Instan CE = new Naivesingleton ();
    }
    
    return instance
  }
}

The above code has at least one problem: Multiple objects may be created in a multithreaded concurrency scenario. A reasonable implementation (but not deferred loading) is the static ' final ' attribute of the class. As follows:

Final property of the class.
Package com.javacodegeeks.advanced.construction.patterns;

public class Eagersingleton {
  private static final Eagersingleton instance = new Eagersingleton ();
  
  Private Eagersingleton () {    
  } public
  
  static Eagersingleton getinstance () {return
    instance;
  }
}

If you don't want to waste precious resources, if you want a single instance object to be created only when you really need it, use an explicit synchronization method that may reduce concurrency in multithreaded environments (more details about Java concurrency will be detailed in Java Advanced 9-Concurrency best Practices).

Package com.javacodegeeks.advanced.construction.patterns;

public class Lazysingleton {
  private static Lazysingleton instance;
  
  Private Lazysingleton () {    
  } public
  
  static synchronized Lazysingleton getinstance () {
    if (instance = null) { C7/>instance = new Lazysingleton ();
    }
    
    return instance
  }
}

Now, in many scenarios, the single case pattern is no longer considered a good choice because they make the code less testable. Additionally, the generation of dependency injection patterns makes the single case pattern unnecessary.

4.2 Tool class/Auxiliary class

Tool class/Helper class patterns are quite popular among Java developers. Its core idea is to use a class that is not instantiated (by declaring the private construct method), optional final (more details on declaring the final class will be described in detail in the Java Advanced 3-class and interface design) keywords and static methods. Examples are as follows:

Package com.javacodegeeks.advanced.construction.patterns;

Public final class Helperclass {
  private helperclass () {    
  } public
  
  static void HelperMethod1 () {
    //Me Thod body here
  } public
  
  static void HelperMethod2 () {
    //method body here
  }
}

Many experienced developers believe that this pattern makes the tool Class A container for a variety of unrelated methods. Because some methods do not have proper placement but need to be used by other classes, they are mistakenly placed in the tool class. This design should also be avoided in most scenarios: there is always a better way to reuse the code and keep it clear and concise.

4.3 Factory mode

The factory model proved to be an extremely powerful tool for developers, and there are many ways to implement it in Java: Factory methods and abstract factories. The simplest example is to use the static method to return an instance of a particular class (Factory method) as follows:

Package com.javacodegeeks.advanced.construction.patterns;

public class Book {
  private book (final string title) {
  } public   

  static book Newbook (final string title) {
   return new book (title);
  }


While using this method improves the readability of your code, it is often argued that it is difficult to give a richer scenario to the Newbook factory approach. Another way to implement a factory pattern is to use an interface or abstract class (abstract factory). As follows, we define a factory interface:

Public interface Bookfactory {book
  newbook ();
}

Depending on the photo gallery, we can have a variety of different Newbook implementations:

public class Library implements Bookfactory {
  @Override public book
  Newbook () {return
    new Paperbook ();
  }
}

public class Kindlelibrary implements Bookfactory {
  @Override public book
  Newbook () {return
    new Kindlebook ( );
  }
}

Now, the different implementations of Bookfactory mask the differences in the specific book, but provide a common Newbook method.

4.4 Dependency Injection

Dependency Injection (also known as control reversal) is considered by class designers to be a good design practice: If some class instances depend on instances of other classes, those that are dependent should be provided (injected) by the constructor method (or setter method, policy, etc.), rather than by the instance itself. Let's take a look at the following code:

Package com.javacodegeeks.advanced.construction.patterns;

Import Java.text.DateFormat;
Import java.util.Date;

public class Dependant {
  private final DateFormat format = Dateformat.getdateinstance ();
  
  Public String Format (final date date) {return
    Format.format (date);
  }
}

The dependant class requires an instance of a DateFormat class and is obtained by dateformat.getdateinstance () when the object is instantiated. The better way to do the same thing is by constructing the parameters of the method:

Package com.javacodegeeks.advanced.construction.patterns;

Import Java.text.DateFormat;
Import java.util.Date;

public class Dependant {
  private final dateformat format;
  
  Public dependant (final DateFormat format) {
    This.format = format;
  }
  
  Public String Format (final date date) {return
    Format.format (date);
  }
}

In the example above, all dependencies of a class instance are provided externally, which makes it easy to adjust DateFormat and easily write test code.

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.