zoukankan      html  css  js  c++  java
  • Different ways to create an object in Java

    Different ways to create an object in Java

     

    You must have used the “new” operator to create an Object of a Class. But is it the only way to create an Object?

    Simple Answers is NO, then in how many ways we can create Object of a Class. There are several like

    • Using New keyword
    • Using New Instance (Reflection)
    • Using Clone
    • Using Deserilization
    • Using ClassLoader
    • … don’t know :)

    Now we will explore the different ways of creating the Object except new Operator.

    Using New Keyword

    Using new keyword is the most basic way to create an object. Use new keyword to create and Object of class.

     

    Using New Instance (Reflection)

    Have you ever tried to connect to any DB using JDBC driver in Java, If your answer is yes then you must have seen “Class.forName“. We can also use it to create the object of a class. Class.forName actually loads the class in Java but doesn’t create any Object. To Create an Object of the Class you have to use newInstance method of Class class.

    Note*: If you want to create Object in this way class needs to have public default Constructor.

    Using Clone

    We can also use Clone() method to create a copy of an existing Object.

     Note*:

    • Here we are creating the clone of an existing Object and not any new Object. 
    • Clone method is declared protected in Object class. So it can be accessed only in subclass or in same package. That is the reason why it has been overridden here in Class.
    • Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.
     

    Using Object Deserialization

    Object deserialization can also be used to create an Object. It is just the opposite of serializing an Object.

    Using ClassLoader

    We can also use Class Loader to create Object of a Class. This way is some what same as Class.forName option.

  • 相关阅读:
    RecyclerView,ListView first item get focus
    一种粗暴快速的Android全屏幕适配方案(转)
    谈谈单元测试之(一):为什么要进行烦人的单元测试(转)
    SCIgen与野鸡期刊的梗
    百度搜索仍然是【最快解决工作问题的方法】
    搭建minima主题的github博客网站
    本科期间的第一个专利:改卷筒的故事
    学习消费思维的【贫穷与富有】
    我的联系方式
    学习 GitHub 有什么好处?
  • 原文地址:https://www.cnblogs.com/hephec/p/4556652.html
Copyright © 2011-2022 走看看