{"id":43663,"date":"2015-09-18T21:43:03","date_gmt":"2015-09-18T18:43:03","guid":{"rendered":"http:\/\/www.javacodegeeks.com\/?p=43663"},"modified":"2023-12-06T12:01:53","modified_gmt":"2023-12-06T10:01:53","slug":"how-to-create-and-destroy-objects","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html","title":{"rendered":"How to create and destroy objects"},"content":{"rendered":"<p><em>This article is part of our Academy Course titled <a href=\"http:\/\/www.javacodegeeks.com\/2015\/09\/advanced-java.html\">Advanced Java<\/a>.<\/p>\n<p>This course is designed to help you make the most effective use of Java. It discusses advanced topics, including object creation, concurrency, serialization, reflection and many more. It will guide you through your journey to Java mastery! Check it out <a href=\"http:\/\/www.javacodegeeks.com\/2015\/09\/advanced-java.html\">here<\/a>!<\/em><\/p>\n<div class=\"toc\">\n<h4>Table Of Contents<\/h4>\n<dl>\n<dt><a href=\"#introduction\">1. Introduction<\/a><\/dt>\n<dt><a href=\"#instance_con\">2. Instance Construction<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#implict\">2.1. Implicit (Generated) Constructor<\/a><\/dt>\n<dt><a href=\"#without_arguments\">2.2. Constructors without Arguments<\/a><\/dt>\n<dt><a href=\"#with_arguments\">2.3. Constructors with Arguments<\/a><\/dt>\n<dt><a href=\"#initialization_blocks\">2.4. Initialization Blocks<\/a><\/dt>\n<dt><a href=\"#guarantee\">2.5. Construction guarantee<\/a><\/dt>\n<dt><a href=\"#visibility\">2.6. Visibility<\/a><\/dt>\n<dt><a href=\"#garbage\">2.7. Garbage collection<\/a><\/dt>\n<dt><a href=\"#finalizers\">2.8. Finalizers<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#static\">3. Static initialization<\/a><\/dt>\n<dt><a href=\"#patterns\">4. Construction Patterns<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#singleton\">4.1. Singleton<\/a><\/dt>\n<dt><a href=\"#utility\">4.2. Utility\/Helper Class<\/a><\/dt>\n<dt><a href=\"#factory\">4.3. Factory<\/a><\/dt>\n<dt><a href=\"#injection\">4.4. Dependency Injection<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#code\">5. Download the Source Code<\/a><\/dt>\n<dt><a href=\"#next\">6. What&#8217;s next<\/a><\/dt>\n<\/dl>\n<\/div>\n<h2><a name=\"introduction\"><\/a>1. Introduction<\/h2>\n<p>Java programming language, originated in Sun Microsystems and released back in 1995, is one of the most widely used programming languages in the world, according to <a href=\"http:\/\/www.tiobe.com\/index.php\/content\/paperinfo\/tpci\/index.html\">TIOBE Programming Community Index<\/a>. Java is a general-purpose programming language. It is attractive to software developers primarily due to its powerful library and runtime, simple syntax, rich set of supported platforms (Write Once, Run Anywhere &#8211; WORA) and awesome community.<\/p>\n<p>In this tutorial we are going to cover advanced Java concepts, assuming that our readers already have some basic knowledge of the language. It is by no means a complete reference, rather a detailed guide to move your Java skills to the next level.<\/p>\n<p>Along the course, there will be a lot of code snippets to look at. Where it makes sense, the same example will be presented using Java 7 syntax as well as Java 8 one.<\/p>\n<h2><a name=\"instance_con\"><\/a>2. Instance Construction<\/h2>\n<p>Java is object-oriented language and as such the creation of new class instances (objects) is, probably, the most important concept of it. Constructors are playing a central role in new class instance initialization and Java provides a couple of favors to define them.<\/p>\n<h3><a name=\"implict\"><\/a>2.1. Implicit (Generated) Constructor<\/h3>\n<p>Java allows to define a class without any constructors but it does not mean the class will not have any. For example, let us consider this class:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class NoConstructor {\n}\n<\/pre>\n<p>This class has no constructor but Java compiler will generate one implicitly and the creation of new class instances will be possible using <code>new<\/code> keyword.<\/p>\n<pre class=\"brush:java\">final NoConstructor noConstructorInstance = new NoConstructor();<\/pre>\n<h3><a name=\"without_arguments\"><\/a>2.2. Constructors without Arguments<\/h3>\n<p>The constructor without arguments (or no-arg constructor) is the simplest way to do Java compiler\u2019s job explicitly.<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class NoArgConstructor {\n    public NoArgConstructor() {\n        \/\/ Constructor body here\n    }\n}\n<\/pre>\n<p>This constructor will be called once new instance of the class is created using the <code>new<\/code> keyword.<\/p>\n<pre class=\"brush:java\">final NoArgConstructor noArgConstructor = new NoArgConstructor();<\/pre>\n<h3><a name=\"with_arguments\"><\/a>2.3. Constructors with Arguments<\/h3>\n<p>The constructors with arguments are the most interesting and useful way to parameterize new class instances creation. The following example defines a constructor with two arguments.<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class ConstructorWithArguments {\n    public ConstructorWithArguments(final String arg1,final String arg2) {\n        \/\/ Constructor body here\n    }\n}\n<\/pre>\n<p>In this case, when class instance is being created using the <code>new<\/code> keyword, both constructor arguments should be provided.<\/p>\n<pre class=\"brush:java\">final ConstructorWithArguments constructorWithArguments = \n    new ConstructorWithArguments( \"arg1\", \"arg2\" );\n<\/pre>\n<p>Interestingly, the constructors can call each other using the special <code>this<\/code> keyword. It is considered a good practice to chain constructors in such a way as it reduces code duplication and basically leads to having single initialization entry point. As an example, let us add another constructor with only one argument.<\/p>\n<pre class=\"brush:java\">public ConstructorWithArguments(final String arg1) {\n    this(arg1, null);\n}\n<\/pre>\n<h3><a name=\"initialization_blocks\"><\/a>2.4. Initialization Blocks<\/h3>\n<p>Java has yet another way to provide initialization logic using initialization blocks. This feature is rarely used but it is better to know it exists.<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class InitializationBlock {\n    {\n        \/\/ initialization code here\n    }\n}\n<\/pre>\n<p>In a certain way, the initialization block might be treated as anonymous no-arg constructor. The particular class may have multiple initialization blocks and they all will be called in the order they are defined in the code. For example:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class InitializationBlocks {\n    {\n        \/\/ initialization code here\n    }\n\n    {\n        \/\/ initialization code here\n    }\n\n}\n<\/pre>\n<p>Initialization blocks do not replace the constructors and may be used along with them. But it is very important to mention that initialization blocks are always called <strong>before<\/strong> any constructor.<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class InitializationBlockAndConstructor {\n    {\n        \/\/ initialization code here\n    }\n    \n    public InitializationBlockAndConstructor() {\n    }\n}\n<\/pre>\n<h3><a name=\"guarantee\"><\/a>2.5. Construction guarantee<\/h3>\n<p>Java provides certain initialization guarantees which developers may rely on. Uninitialized instance and class (static) variables are automatically initialized to their default values.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<div class=\"wp-caption aligncenter\">\n<table>\n<tbody>\n<tr>\n<td width=\"130\"><strong>Type<\/strong><\/td>\n<td width=\"113\"><strong>Default Value<\/strong><\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>boolean<\/strong><\/td>\n<td width=\"113\">False<\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>byte<\/strong><\/td>\n<td width=\"113\">0<\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>short<\/strong><\/td>\n<td width=\"113\">0<\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>int<\/strong><\/td>\n<td width=\"113\">0<\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>long<\/strong><\/td>\n<td width=\"113\">0L<\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>char<\/strong><\/td>\n<td width=\"113\">\\u0000<\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>float<\/strong><\/td>\n<td width=\"113\">0.0f<\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>double<\/strong><\/td>\n<td width=\"113\">0.0d<\/td>\n<\/tr>\n<tr>\n<td width=\"130\"><strong>object reference<\/strong><\/td>\n<td width=\"113\">null<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"wp-caption-text\">Table 1<\/p>\n<\/div>\n<p>Let us confirm that using following class as a simple example:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class InitializationWithDefaults {\n    private boolean booleanMember;\n    private byte byteMember;\n    private short shortMember;\n    private int intMember;\n    private long longMember;\n    private char charMember;\n    private float floatMember;\n    private double doubleMember;\n    private Object referenceMember;\n\n    public InitializationWithDefaults() {     \n        System.out.println( \"booleanMember = \" + booleanMember );\n        System.out.println( \"byteMember = \" + byteMember );\n        System.out.println( \"shortMember = \" + shortMember );\n        System.out.println( \"intMember = \" + intMember );\n        System.out.println( \"longMember = \" + longMember );\n        System.out.println( \"charMember = \" + \n            Character.codePointAt( new char[] { charMember }, 0  ) );\n        System.out.println( \"floatMember = \" + floatMember );\n        System.out.println( \"doubleMember = \" + doubleMember );\n        System.out.println( \"referenceMember = \" + referenceMember );\n    }\n}\n<\/pre>\n<p>Once instantiated using <code>new<\/code> keyword:<\/p>\n<pre class=\"brush:java\">final InitializationWithDefaults initializationWithDefaults = new InitializationWithDefaults(), <\/pre>\n<p>The following output will be shown in the console:<\/p>\n<pre class=\"brush:java\">booleanMember = false\nbyteMember = 0\nshortMember = 0\nintMember = 0\nlongMember = 0\ncharMember = 0\nfloatMember = 0.0\ndoubleMember = 0.0\nreferenceMember = null\n<\/pre>\n<h3><a name=\"visibility\"><\/a>2.6. Visibility<\/h3>\n<p>Constructors are subject to Java visibility rules and can have access control modifiers which determine if other classes may invoke a particular constructor.<\/p>\n<div class=\"wp-caption aligncenter\">\n<table>\n<tbody>\n<tr>\n<td width=\"108\"><strong>Modifier<\/strong><\/td>\n<td width=\"105\"><strong>Package<\/strong><\/td>\n<td width=\"113\"><strong>Subclass<\/strong><\/td>\n<td width=\"113\"><strong>Everyone Else<\/strong><\/td>\n<\/tr>\n<tr>\n<td width=\"108\"><strong>public<\/strong><\/td>\n<td width=\"105\">accessible<\/td>\n<td width=\"113\">accessible<\/td>\n<td width=\"113\">accessible<\/td>\n<\/tr>\n<tr>\n<td width=\"108\"><strong>protected<\/strong><\/td>\n<td width=\"105\">accessible<\/td>\n<td width=\"113\">accessible<\/td>\n<td width=\"113\"><strong>not accessible<\/strong><\/td>\n<\/tr>\n<tr>\n<td width=\"108\"><strong>&lt;no modifier&gt;<\/strong><\/td>\n<td width=\"105\">accessible<\/td>\n<td width=\"113\"><strong>not accessible<\/strong><\/td>\n<td width=\"113\"><strong>not accessible<\/strong><\/td>\n<\/tr>\n<tr>\n<td width=\"108\"><strong>private<\/strong><\/td>\n<td width=\"105\"><strong>not accessible<\/strong><\/td>\n<td width=\"113\"><strong>not accessible<\/strong><\/td>\n<td width=\"113\"><strong>not accessible<\/strong><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"wp-caption-text\">Table 2<\/p>\n<\/div>\n<h3><a name=\"garbage\"><\/a>2.7. Garbage collection<\/h3>\n<p>Java (and JVM in particular) uses automatic garbage collection. To put it simply, whenever new objects are created, the memory is automatically allocated for them. Consequently, whenever the objects are not referenced anymore, they are destroyed and their memory is reclaimed.<\/p>\n<p>Java garbage collection is generational and is based on assumption that most objects die young (not referenced anymore shortly after their creation and as such can be destroyed safely). Most developers used to believe that objects creation in Java is slow and instantiation of the new objects should be avoided as much as possible. In fact, it does not hold true: the objects creation in Java is quite cheap and fast. What is expensive though is an unnecessary creation of long-lived objects which eventually may fill up old generation and cause stop-the-world garbage collection.<\/p>\n<h3><a name=\"finalizers\"><\/a>2.8. Finalizers<\/h3>\n<p>So far we have talked about constructors and objects initialization but have not actually mentioned anything about their counterpart: objects destruction. That is because Java uses garbage collection to manage objects lifecycle and it is the responsibility of garbage collector to destroy unnecessary objects and reclaim the memory.<\/p>\n<p>However, there is one particular feature in Java called <strong>finalizers<\/strong> which resemble a bit the destructors but serves the different purpose of performing resources cleanup. <strong>Finalizers<\/strong> are considered to be a dangerous feature (which leads to numerous side-effects and performance issues). Generally, they are not necessary and should be avoided (except very rare cases mostly related to native objects). A much better alternative to <strong>finalizers<\/strong> is the introduced by <strong>Java 7<\/strong> language construct called <strong><a href=\"http:\/\/docs.oracle.com\/javase\/tutorial\/essential\/exceptions\/tryResourceClose.html\">try-with-resources<\/a><\/strong> and <code><a href=\"http:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/AutoCloseable.html\">AutoCloseable<\/a><\/code> interface which allows to write clean code like this:<\/p>\n<pre class=\"brush:java\">try ( final InputStream in = Files.newInputStream( path ) ) {\n    \/\/ code here\n}\n<\/pre>\n<h2><a name=\"static\"><\/a>3. Static initialization<\/h2>\n<p>So far we have looked through class instance construction and initialization. But Java also supports class-level initialization constructs called <strong>static initializers<\/strong>. There are very similar to the initialization blocks except for the additional <code>static<\/code> keyword. Please notice that static initialization is performed once per class-loader. For example:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class StaticInitializationBlock {\n    static {\n        \/\/ static initialization code here\n    }\n}\n<\/pre>\n<p>Similarly to initialization blocks, you may include any number of static initializer blocks in the class definition and they will be executed in the order in which they appear in the code. For example:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction;\n\npublic class StaticInitializationBlocks {\n    static {\n        \/\/ static initialization code here\n    }\n\n    static {\n        \/\/ static initialization code here\n    }\n}\n<\/pre>\n<p>Because static initialization block can be triggered from multiple parallel threads (when the loading of the class happens in the first time), Java runtime guarantees that it will be executed only once and in thread-safe manner.<\/p>\n<h2><a name=\"patterns\"><\/a>4. Construction Patterns<\/h2>\n<p>Over the years a couple of well-understood and widely applicable construction (or creation) patterns have emerged within Java community. We are going to cover the most famous of them: singleton, helpers, factory and dependency injection (also known as inversion of control).<\/p>\n<h3><a name=\"singleton\"><\/a>4.1. Singleton<\/h3>\n<p>Singleton is one of the oldest and controversial patterns in software developer\u2019s community. Basically, the main idea of it is to ensure that only one single instance of the class could be created at any given time. Being so simple however, singleton raised a lot of the discussions about how to make it right and, in particular, thread-safe. Here is how a naive version of singleton class may look like:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction.patterns;\n\npublic class NaiveSingleton {\n    private static NaiveSingleton instance;\n    \n    private NaiveSingleton() {        \n    }\n    \n    public static NaiveSingleton getInstance() {\n        if( instance == null ) {\n            instance = new NaiveSingleton();\n        }\n        \n        return instance;\n    }\n}\n<\/pre>\n<p>At least one problem with this code is that it may create many instances of the class if called concurrently by multiple threads. One of the ways to design singleton properly (but in non-lazy fashion) is using the <code>static<\/code> <code>final<\/code> property of the class.<\/p>\n<pre class=\"brush:java\">final property of the class.\npackage com.javacodegeeks.advanced.construction.patterns;\n\npublic class EagerSingleton {\n    private static final EagerSingleton instance = new EagerSingleton();\n    \n    private EagerSingleton() {        \n    }\n    \n    public static EagerSingleton getInstance() {\n        return instance;\n    }\n}\n<\/pre>\n<p>If you do not want to waste your resources and would like your singletons to be lazily created when they are really needed, the explicit synchronization is required, potentially leading to lower concurrency in a multithreaded environments (more details about concurrency in Java will be discussing in <strong>part 9<\/strong> of the tutorial, <strong>Concurrency best practices<\/strong>).<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction.patterns;\n\npublic class LazySingleton {\n    private static LazySingleton instance;\n    \n    private LazySingleton() {        \n    }\n    \n    public static synchronized LazySingleton getInstance() {\n        if( instance == null ) {\n            instance = new LazySingleton();\n        }\n        \n        return instance;\n    }\n}\n<\/pre>\n<p>Nowadays, singletons are not considered to be a good choice in most cases, primarily because they are making a code very hard to test. The domination of dependency injection pattern (please see the <strong>Dependency Injection<\/strong> section below) also makes singletons unnecessary.<br \/>\n[ulp id=&#8217;w6F4W4SAMiyTapBF&#8217;]<br \/>\n&nbsp;<\/p>\n<h3><a name=\"utility\"><\/a>4.2. Utility\/Helper Class<\/h3>\n<p>The utility or helper classes are quite popular pattern used by many Java developers. Basically, it represents the non-instantiable class (with constructor declared as <code>private<\/code>), optionally declared as <code>final<\/code> (more details about declaring classes as <code>final<\/code> will be provided in <strong>part 3<\/strong> of the tutorial, <strong>How to design Classes and Interfaces<\/strong>) and contains <code>static<\/code> methods only. For example:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction.patterns;\n\npublic final class HelperClass {\n    private HelperClass() {        \n    }\n    \n    public static void helperMethod1() {\n        \/\/ Method body here\n    }\n    \n    public static void helperMethod2() {\n        \/\/ Method body here\n    }\n}\n<\/pre>\n<p>From seasoned software developer standpoint, such helpers often become containers for all kind of non-related methods which have not found other place to be put in but should be shared somehow and used by other classes. Such design decisions should be avoided in most cases: it is always possible to find another way to reuse the required functionality, keeping the code clean and concise.<\/p>\n<h3><a name=\"factory\"><\/a>4.3. Factory<\/h3>\n<p>Factory pattern is proven to be extremely useful technique in the hands of software developers. As such, it has several flavors in Java, ranging from <strong>factory method<\/strong> to <strong>abstract factory<\/strong>. The simplest example of factory pattern is a <code>static<\/code> method which returns new instance of a particular class (<strong>factory method<\/strong>). For example:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction.patterns;\n\npublic class Book {\n    private Book( final String title) {\n    }     \n\n    public static Book newBook( final String title ) { \n        return new Book( title );\n    }\n}\n<\/pre>\n<p>The one may argue that it does not make a lot of sense to introduce the <code>newBook<\/code> <strong>factory method<\/strong> but using such a pattern often makes the code more readable. Another variance of factory pattern involves interfaces or abstract classes (<strong>abstract factory<\/strong>). For example, let us define a <strong>factory interface<\/strong>:<\/p>\n<pre class=\"brush:java\">public interface BookFactory {\n    Book newBook();\n}\n<\/pre>\n<p>With couple of different implementations, depending on the library type:<\/p>\n<pre class=\"brush:java\">public class Library implements BookFactory {\n    @Override\n    public Book newBook() {\n        return new PaperBook();\n    }\n}\n\npublic class KindleLibrary implements BookFactory {\n    @Override\n    public Book newBook() {\n        return new KindleBook();\n    }\n}\n<\/pre>\n<p>Now, the particular class of the <code>Book<\/code> is hidden behind <code>BookFactory<\/code> interface implementation, still providing the generic way to create books.<\/p>\n<h3><a name=\"injection\"><\/a>4.4. Dependency Injection<\/h3>\n<p>Dependency injection (also known as inversion of control) is considered as a good practice for class designers: if some class instance depends on the other class instances, those dependencies should be provided (injected) to it by means of constructors (or setters, strategies, etc.) but not created by the instance itself. Let us consider the following example:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction.patterns;\n\nimport java.text.DateFormat;\nimport java.util.Date;\n\npublic class Dependant {\n    private final DateFormat format = DateFormat.getDateInstance();\n    \n    public String format( final Date date ) {\n        return format.format( date );\n    }\n}\n<\/pre>\n<p>The class <code>Dependant<\/code> needs an instance of DateFormat and it just creates one by calling <code>DateFormat.getDateInstance()<\/code> at construction time. The better design would be to use constructor argument to do the same thing:<\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.advanced.construction.patterns;\n\nimport java.text.DateFormat;\nimport java.util.Date;\n\npublic class Dependant {\n    private final DateFormat format;\n    \n    public Dependant( final DateFormat format ) {\n        this.format = format;\n    }\n    \n    public String format( final Date date ) {\n        return format.format( date );\n    }\n}\n<\/pre>\n<p>In this case the class has all its dependencies provided from outside and it would be very easy to change date format and write test cases for it.<\/p>\n<h2><a name=\"code\"><\/a>5. Download the Source Code<\/h2>\n<ul>\n<li>You may download the source code here: <a href=\"http:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2015\/09\/com.javacodegeeks.advanced.java_.zip\">com.javacodegeeks.advanced.java<\/a><\/li>\n<\/ul>\n<h2><a name=\"next\"><\/a>6. What&#8217;s next<\/h2>\n<p>In this part of the tutorial we have looked at classes and class instances construction and initialization techniques, along the way covering several widely used patterns. In the next part we are going to dissect the <code>Object<\/code> class and usage of its well-known methods: <code>equals<\/code>, <code>hashCode<\/code>, <code>toString<\/code> and <code>clone<\/code>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article is part of our Academy Course titled Advanced Java. This course is designed to help you make the most effective use of Java. It discusses advanced topics, including object creation, concurrency, serialization, reflection and many more. It will guide you through your journey to Java mastery! Check it out here! Table Of Contents &hellip;<\/p>\n","protected":false},"author":141,"featured_media":148,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[343,88,580,557,65],"class_list":["post-43663","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-core-java","tag-annotations","tag-concurrency","tag-generics","tag-reflection","tag-serialization"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to create and destroy objects - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"This article is part of our Academy Course titled Advanced Java. This course is designed to help you make the most effective use of Java. It discusses\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to create and destroy objects - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"This article is part of our Academy Course titled Advanced Java. This course is designed to help you make the most effective use of Java. It discusses\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2015-09-18T18:43:03+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-06T10:01:53+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/java-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Andrey Redko\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Andrey Redko\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html\"},\"author\":{\"name\":\"Andrey Redko\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/771a6504862edc45322776832cbce413\"},\"headline\":\"How to create and destroy objects\",\"datePublished\":\"2015-09-18T18:43:03+00:00\",\"dateModified\":\"2023-12-06T10:01:53+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html\"},\"wordCount\":1770,\"commentCount\":11,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/java-logo.jpg\",\"keywords\":[\"Annotations\",\"Concurrency\",\"Generics\",\"Reflection\",\"Serialization\"],\"articleSection\":[\"Core Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html\",\"name\":\"How to create and destroy objects - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/java-logo.jpg\",\"datePublished\":\"2015-09-18T18:43:03+00:00\",\"dateModified\":\"2023-12-06T10:01:53+00:00\",\"description\":\"This article is part of our Academy Course titled Advanced Java. This course is designed to help you make the most effective use of Java. It discusses\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/java-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/java-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/09\\\/how-to-create-and-destroy-objects.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Core Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\\\/core-java\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"How to create and destroy objects\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/771a6504862edc45322776832cbce413\",\"name\":\"Andrey Redko\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/16419ce8394173028eddaeb992859862bab50cfcf74589fa9bb9a3dd8bb27518?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/16419ce8394173028eddaeb992859862bab50cfcf74589fa9bb9a3dd8bb27518?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/16419ce8394173028eddaeb992859862bab50cfcf74589fa9bb9a3dd8bb27518?s=96&d=mm&r=g\",\"caption\":\"Andrey Redko\"},\"description\":\"Andriy is a well-grounded software developer with more then 12 years of practical experience using Java\\\/EE, C#\\\/.NET, C++, Groovy, Ruby, functional programming (Scala), databases (MySQL, PostgreSQL, Oracle) and NoSQL solutions (MongoDB, Redis).\",\"sameAs\":[\"http:\\\/\\\/aredko.blogspot.com\\\/\",\"http:\\\/\\\/ca.linkedin.com\\\/in\\\/aredko\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/andrey-redko\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to create and destroy objects - Java Code Geeks","description":"This article is part of our Academy Course titled Advanced Java. This course is designed to help you make the most effective use of Java. It discusses","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html","og_locale":"en_US","og_type":"article","og_title":"How to create and destroy objects - Java Code Geeks","og_description":"This article is part of our Academy Course titled Advanced Java. This course is designed to help you make the most effective use of Java. It discusses","og_url":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2015-09-18T18:43:03+00:00","article_modified_time":"2023-12-06T10:01:53+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/java-logo.jpg","type":"image\/jpeg"}],"author":"Andrey Redko","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Andrey Redko","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html"},"author":{"name":"Andrey Redko","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/771a6504862edc45322776832cbce413"},"headline":"How to create and destroy objects","datePublished":"2015-09-18T18:43:03+00:00","dateModified":"2023-12-06T10:01:53+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html"},"wordCount":1770,"commentCount":11,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/java-logo.jpg","keywords":["Annotations","Concurrency","Generics","Reflection","Serialization"],"articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html","url":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html","name":"How to create and destroy objects - Java Code Geeks","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/java-logo.jpg","datePublished":"2015-09-18T18:43:03+00:00","dateModified":"2023-12-06T10:01:53+00:00","description":"This article is part of our Academy Course titled Advanced Java. This course is designed to help you make the most effective use of Java. It discusses","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/java-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/java-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/2015\/09\/how-to-create-and-destroy-objects.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/www.javacodegeeks.com\/category\/java"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https:\/\/www.javacodegeeks.com\/category\/java\/core-java"},{"@type":"ListItem","position":4,"name":"How to create and destroy objects"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/771a6504862edc45322776832cbce413","name":"Andrey Redko","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/16419ce8394173028eddaeb992859862bab50cfcf74589fa9bb9a3dd8bb27518?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/16419ce8394173028eddaeb992859862bab50cfcf74589fa9bb9a3dd8bb27518?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/16419ce8394173028eddaeb992859862bab50cfcf74589fa9bb9a3dd8bb27518?s=96&d=mm&r=g","caption":"Andrey Redko"},"description":"Andriy is a well-grounded software developer with more then 12 years of practical experience using Java\/EE, C#\/.NET, C++, Groovy, Ruby, functional programming (Scala), databases (MySQL, PostgreSQL, Oracle) and NoSQL solutions (MongoDB, Redis).","sameAs":["http:\/\/aredko.blogspot.com\/","http:\/\/ca.linkedin.com\/in\/aredko"],"url":"https:\/\/www.javacodegeeks.com\/author\/andrey-redko"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/43663","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/141"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=43663"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/43663\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/148"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=43663"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=43663"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=43663"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}