{"id":77617,"date":"2020-04-06T15:29:37","date_gmt":"2020-04-06T09:59:37","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=77617"},"modified":"2020-04-06T15:29:37","modified_gmt":"2020-04-06T09:59:37","slug":"java-object-creation","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/","title":{"rendered":"Java Object Creation &#8211; Learn to Create Objects with Different Ways"},"content":{"rendered":"<p>We know that an object is an identifiable entity which is an instance of the class. Today this article will guide you on Object Creation in Java in different ways. We know that without creating and instantiating object there is no use of creating a class.<\/p>\n<p>A class does not occupy a memory while we create it. The memory is allocated to it only when we create its object. In Java, object creation is not limited to a single way, but there are several ways to create it. So without any further delay let\u2019s start exploring the ways to create an object.<\/p>\n<h4>What is an Object?<\/h4>\n<p>An object is a real-world entity that has some characteristics and behavior. For example, in real-life a car is an object which has characteristics like brand name, color, engine type, average, etc, and attributes like drive, brake, stand.<\/p>\n<p>The objects in Java programming are similar to the real-life objects that have attributes (properties) and behavior (methods or functions).<\/p>\n<h4>Characteristics of an Object<\/h4>\n<p>We can define an object by three characteristics:<\/p>\n<ul>\n<li><strong>State:<\/strong> The state of an object represents the value stored in the object.<\/li>\n<li><strong>Behavior:<\/strong> The behavior of an object represents functionality performed by an object. For example, running, sitting, etc.<\/li>\n<li><strong>Identity:<\/strong> The identity of an object is represented by a unique ID. The JVM internally uses this unique ID to identify the object uniquely. And, this unique ID is not visible to the external user.<\/li>\n<\/ul>\n<h3>Java Object Creation<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/04\/ways-to-create-object-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-78071\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/04\/ways-to-create-object-in-java.jpg\" alt=\"\" width=\"802\" height=\"420\" \/><\/a><\/p>\n<p>In Java, we can create objects with 6 different methods which are:<\/p>\n<ul>\n<li>By <strong>new<\/strong> keyword<\/li>\n<li>By <strong>newInstance()<\/strong> method of <strong>Class<\/strong> class<\/li>\n<li>By <strong>newInstance()<\/strong> method of <strong>constructor<\/strong> class<\/li>\n<li>By <strong>clone()<\/strong> method<\/li>\n<li>By <strong>deserialization<\/strong><\/li>\n<li>By <strong>factory<\/strong> method<\/li>\n<\/ul>\n<p>Let\u2019s start discussing each method of creating an object with examples.<\/p>\n<h5>1. Java Object Creation by new keyword<\/h5>\n<p>It is the most simple and common way of creating an object of a class. By using the <strong>new<\/strong> keyword, we can call any type of constructor of the class that is, either the parameterized constructor or non-parameterized constructor.<\/p>\n<p><em><strong>Dive a little deep into the concept of Java Constructor with Techvidvan.<\/strong><\/em><\/p>\n<p><strong>Let\u2019s see the syntax to create an object using the new keyword:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">ClassName ObjectName = new ClassName();<\/pre>\n<p><strong>Code to create an object using the new keyword :<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.objectcreation;\npublic class NewKeyword\n{\n  String name = \"TechVidvan Java Tutorial\";\n  public static void main(String[] args)\n  {\n    \/\/Creating object using new keyword\n    NewKeyword obj = new NewKeyword();\n\n    \/\/Accessing the class variable using the object\n    System.out.println(obj.name);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">TechVidvan Java Tutorial<\/div>\n<h5>2. Java Object Creation by newInstance() method of Class class<\/h5>\n<p>This is another technique to create an object of the class. We use the newInstance() method of a Class class to create an object. This newInstance() method calls the no-arg constructor of the class to create the object.<\/p>\n<p><strong>Syntax to create an object by a newInstance() of Class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">Class cls = Class.forName(\"ClassName\");\nClassName objectName = (ClassName) cls.newInstance();<\/pre>\n<p><strong>Code to create an object using the newInstance() method of Class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.objectcreation;\npublic class NewInstanceMethod\n{\n  String name = \"TechVidvan Java Tutorial\";\n  public static void main(String[] args)\n  {\n    try\n    {\n      Class cls = \t\t\t\t\t   Class.forName(\"com.techvidvan.objectcreation.NewInstanceMethod\");\n      NewInstanceMethod obj =(NewInstanceMethod) cls.newInstance();\n      System.out.println(obj.name);\n    }\n    catch (Exception e)\n    {\n      e.printStackTrace();\n    }\n\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">TechVidvan Java Tutorial<\/div>\n<h5>3. Java Object Creation by newInstance() method of Constructor class<\/h5>\n<p>We can also use the newInstance() method of <strong>java.lang.reflect.Constructor<\/strong> class to create an object. The newInstance() method of the Constructor class is similar to the newInstance() method of the Class class.<\/p>\n<p><strong>Syntax of using newInstance() method of Constructor class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">Constructor&lt;ClassName&gt; constructor = ClassName.class.getConstructor();\nClassName objectName = constructor.newInstance();<\/pre>\n<p><strong>Code to create an object using the newInstance() method of Constructor:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.objectcreation;\nimport java.lang.reflect.*;\npublic class NewInstanceMethod\n{\n  private String name;\n  public void setName(String name)\n  {\n    this.name = name;\n  }\n  public static void main(String[] args)\n    {\n    try\n    {\n      Constructor&lt;NewInstanceMethod&gt; constructor = \t\t\t\t\t \n                        NewInstanceMethod.class.getDeclaredConstructor();\n      NewInstanceMethod obj = constructor.newInstance();\n      obj.setName(\"TechVidvan Java Tutorial\");\n      System.out.println(obj.name);\n    }\n    catch (Exception e)\n    {\n      e.printStackTrace();\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">TechVidvan Java Tutorial<\/div>\n<h5>4. Java Object Creation by clone() method<\/h5>\n<p>When we call the <strong>clone()<\/strong> method through an object, the Java compiler automatically creates a new object of that class. JVM actually copies all content of the older object into the newly created object.<\/p>\n<p>To use the clone() method on an object we have to implement the Cloneable interface and override the clone() method in our class.<\/p>\n<p><strong>Syntax of using the clone() method to create an object:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">ClassName object1 = new ClassName();\nClassName object2 = (ClassName) object1.clone();<\/pre>\n<p><strong>Code to create an object using the clone() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.objectcreation;\npublic class CloneMethod implements Cloneable\n{\n  @Override\n  protected Object clone() throws CloneNotSupportedException\n  {\n    return super.clone();\n  }\n  String name = \"TechVidvan Java Tutorial\";\n  public static void main(String[] args)\n  {\n    CloneMethod obj1 = new CloneMethod();\n    try\n    {\n      CloneMethod obj2 = (CloneMethod) obj1.clone();\n      System.out.println(obj2.name);\n    }\n    catch (CloneNotSupportedException e)\n    {\n      e.printStackTrace();\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">TechVidvan Java Tutorial<\/div>\n<h5>5. Java Object Creation using deserialization<\/h5>\n<p>When we serialize an object and then deserialize it, JVM creates a new object. To deserialize an object, we need to implement the java.io.Serializable.<\/p>\n<p>Create <strong>Employee.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.objectcreation;\npublic class Employee implements java.io.Serializable\n{\n  public String name;\n  public int id;\n\n  public void mailCheck() {\n  }\n\n}<\/pre>\n<p><strong>Code to serialize an object:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.objectcreation;\nimport java.io.*;\npublic class Serialization\n{\n  public static void main(String [] args)\n  {\n    Employee e = new Employee();\n    e.name = \"Ayush Verma\";\n    e.id=101;\n\n    try\n    {\n      FileOutputStream fileOut = new \t\t\tFileOutputStream(\"\/tmp\/employee.ser\");\n      ObjectOutputStream out = new ObjectOutputStream(fileOut);\n      out.writeObject(e);\nout.close();\n      fileOut.close();\n      System.out.printf(\"Serialized data is saved in \/tmp\/employee.ser\");\n    } catch (IOException i)\n    {\n      i.printStackTrace();\n    }\n  }\n}\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>Serialized data is saved in \/tmp\/employee.ser<\/p>\n<\/div>\n<p><strong>Code to deserialize an object:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.objectcreation;\nimport java.io.*;\npublic class Deserialization\n{\n  public static void main(String [] args)\n  {\n    Employee e = null;\n    try\n    {\n      FileInputStream fileIn = new \t\t\tFileInputStream(\"\/tmp\/employee.ser\");\n      ObjectInputStream in = new ObjectInputStream(fileIn);\n      e = (Employee) in.readObject();\n      in.close();\n      fileIn.close();\n    } catch (Exception ex)\n    {\n\n      System.out.println(\"Employee class not found\");\n      ex.printStackTrace();\n      return;\n    }\n    System.out.println(\"Deserialized Employee...\");\n    System.out.println(\"Name: \" + e.name);\n    System.out.println(\"Id: \" + e.id);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Deserialized Employee\u2026<br \/>\nName: Ayush Verma<br \/>\nId: 101<\/div>\n<h3>Summary<\/h3>\n<p>An object is a real-time entity that shows its characteristics and behavior. We learned different ways to create an object of a class in Java.<\/p>\n<p>The most commonly used method of creating an object is the new operator, but there are many more techniques to create an object. We discuss all the ways of creating an object with the help of syntax and examples.<\/p>\n<p>Thank you for reading our article. Do share your feedback through the comment section below.<\/p>\n<p>Keep Learning \ud83d\ude42<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We know that an object is an identifiable entity which is an instance of the class. Today this article will guide you on Object Creation in Java in different ways. We know that without&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":78071,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[2228,2229,2230,2231,2232,2233,2234,2235],"class_list":["post-77617","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-object-creation","tag-object-creation-in-java","tag-using-clone-method","tag-using-deserialization","tag-using-factory-method","tag-using-new-keyword","tag-what-is-object-creation-in-java","tag-what-is-object-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Object Creation - Learn to Create Objects with Different Ways - TechVidvan<\/title>\n<meta name=\"description\" content=\"Java Object Creation- Understand the concept of Object Creation in Java along with its different ways to create an object of a class with syntax &amp; examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Object Creation - Learn to Create Objects with Different Ways - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Java Object Creation- Understand the concept of Object Creation in Java along with its different ways to create an object of a class with syntax &amp; examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-04-06T09:59:37+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/ways-to-create-object-in-java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Object Creation - Learn to Create Objects with Different Ways - TechVidvan","description":"Java Object Creation- Understand the concept of Object Creation in Java along with its different ways to create an object of a class with syntax & examples.","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:\/\/techvidvan.com\/tutorials\/java-object-creation\/","og_locale":"en_US","og_type":"article","og_title":"Java Object Creation - Learn to Create Objects with Different Ways - TechVidvan","og_description":"Java Object Creation- Understand the concept of Object Creation in Java along with its different ways to create an object of a class with syntax & examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-04-06T09:59:37+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/ways-to-create-object-in-java.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Object Creation &#8211; Learn to Create Objects with Different Ways","datePublished":"2020-04-06T09:59:37+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/"},"wordCount":751,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/ways-to-create-object-in-java.jpg","keywords":["Java Object Creation","Object Creation in Java","Using clone() method","Using deserialization","Using Factory Method","Using new Keyword","What is Object Creation in Java","what is object in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-object-creation\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/","url":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/","name":"Java Object Creation - Learn to Create Objects with Different Ways - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/ways-to-create-object-in-java.jpg","datePublished":"2020-04-06T09:59:37+00:00","description":"Java Object Creation- Understand the concept of Object Creation in Java along with its different ways to create an object of a class with syntax & examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-object-creation\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/ways-to-create-object-in-java.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/04\/ways-to-create-object-in-java.jpg","width":802,"height":420,"caption":"java object creation"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-object-creation\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Object Creation &#8211; Learn to Create Objects with Different Ways"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/77617","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=77617"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/77617\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/78071"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=77617"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=77617"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=77617"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}