Several ways to create objects in Java _java

Source: Internet
Author: User
Tags arrays redis

Sometimes, you may also encounter such interview questions, such as:

What are some ways to create objects in Java?

What are some other ways to create Java objects besides new?

This article unifies the example, gives several Java to create the object the method, here we go~~~~

Using new to create

This is the most commonly used one. Such as:

Book book = new book ();

Examples are as follows:

Package test;
Import java.io.Serializable;

Import java.util.List;  /** * @author Wangmengjun * * */public class book implements serializable{private static final long Serialversionuid

  = -6212470156629515269l;

  /** Title */private String name;

  /** Author * * Private list<string> authors;

  /**isbn*/private String ISBN;

  /** prices/private float price; Public book () {}/** * @param name * @param authors * @param ISBN * @param price/public book (STR
    ing name, list<string> authors, String ISBN, float price) {this.name = name;
    this.authors = authors;
    THIS.ISBN = ISBN;
  This.price = Price;
  }/** * @return the name */public String GetName () {return name;
  }/** * @param name the name to set */public void SetName (String name) {this.name = name;
  }/** * @return The authors * * * public list<string> GetAuthors () {return authors; }/** * @param authors the authors to Set */public void setauthors (list<string> authors) {this.authors = authors;
  /** * @return The ISBN/Public String getisbn () {return ISBN;
  /** * @param ISBN the ISBN to set */public void Setisbn (String ISBN) {this.isbn = ISBN;
  /** * @return The price */public float GetPrice () {return price;
  /** * @param price "price" to set */public void Setprice (float price) {this.price = Price; }/* (non-javadoc) * @see java.lang.object#tostring () * * * @Override public String toString () {return "Boo"
  K [name= "+ name +", authors= "+ authors +", isbn= "+ ISBN +", price= "+ Price +"] ";

 }

}
    /**
     * 1. Create object using new
    /book Book1 = new book ();
    Book1.setname ("Redis");
    Book1.setauthors (Arrays.aslist ("Eric", "John"));
    Book1.setprice (59.00f);
    BOOK1.SETISBN ("abbbb-qq677868686-hsdkhfkhkh-2324234");
    System.out.println (BOOK1);

Using Object.clone ()

If you want to invoke the Clone method, the object needs to implement the Cloneable interface and override the Clone () method.

The revised book class is as follows:

Package test;
Import java.io.Serializable;

Import java.util.List; /** * @author Wangmengjun * * */public class book implements Serializable, cloneable {private static final long Seri

  Alversionuid = -6212470156629515269l;

  /** Title */private String name;

  /** Author * * Private list<string> authors;

  /**isbn*/private String ISBN;

  /** prices/private float price; Public book () {}/** * @param name * @param authors * @param ISBN * @param price/public book (STR
    ing name, list<string> authors, String ISBN, float price) {this.name = name;
    this.authors = authors;
    THIS.ISBN = ISBN;
  This.price = Price;
  }/** * @return the name */public String GetName () {return name;
  }/** * @param name the name to set */public void SetName (String name) {this.name = name;
  }/** * @return The authors * * * public list<string> GetAuthors () {return authors; }/** * @param authors thE authors to set */public void setauthors (list<string> authors) {this.authors = authors;
  /** * @return The ISBN/Public String getisbn () {return ISBN;
  /** * @param ISBN the ISBN to set */public void Setisbn (String ISBN) {this.isbn = ISBN;
  /** * @return The price */public float GetPrice () {return price;
  /** * @param price "price" to set */public void Setprice (float price) {this.price = Price; }/* (non-javadoc) * @see java.lang.object#tostring () * * * @Override public String toString () {return "Boo"
  K [name= "+ name +", authors= "+ authors +", isbn= "+ ISBN +", price= "+ Price +"] ";
  @Override protected Object Clone () throws Clonenotsupportedexception {return (book) Super.clone ();

 }

}

Test code

    /**
     * 1. Create object using new
    /book Book1 = new book ();
    Book1.setname ("Redis");
    Book1.setauthors (Arrays.aslist ("Eric", "John"));
    Book1.setprice (59.00f);
    BOOK1.SETISBN ("abbbb-qq677868686-hsdkhfkhkh-2324234");
    System.out.println (BOOK1);

    /**
     * 2. Create object using clone
    /try {book
      Book2 = (book) book1.clone ();
      System.out.println (BOOK2);
    } catch (Clonenotsupportedexception e) {
      //TODO auto-generated catch block
      e.printstacktrace ();
    }

Using Class.newinstance ()

You can use the Class.forName ("xxx.xx"). Newinstance ( ) method or XXX.class.newInstance () to complete.

    /**
     * 3. Use Class.newinstance ();
     */
    try {book
      book3 = (book) class.forname ("Test". Book "). newinstance ();
      System.out.println (BOOK3);

      BOOK3 = Book.class.newInstance ();
      System.out.println (BOOK3);
    } catch (Instantiationexception | illegalaccessexception | ClassNotFoundException e) {
      //TODO auto-generated catch block
      e.printstacktrace ();
    }

Using Contructor.newinstance ()

You can specify constructors to create, such as selecting the first constructor, or you can specify a constructor parameter type to create.

/** * 4. Use Constructor.newinstance ();
      */try {//Select the first constructor to create the book book Book4 = (book) Book.class.getConstructors () [0].newinstance ();

      Book [Name=null, Authors=null, Isbn=null, price=0.0] System.out.println (BOOK4); 
          /** * Invokes the specified constructor creation Object * * Book4 = (book) Book.class.getConstructor (String.class, List.class, String.class, Float.class). newinstance ("New Instance Example", Arrays.aslist ("Wang", "Eric"), "abc1111111-def-33333
      ", 60.00f); Book [Name=new Instance Example, Authors=[wang, Eric], isbn=abc1111111-def-33333, price=60.0] System.out.println (b
    OOK4); catch (Instantiationexception | illegalaccessexception | IllegalArgumentException | InvocationTargetException | SecurityException |
    Nosuchmethodexception e) {//TODO auto-generated catch block E.printstacktrace (); }

Using Class.newinstance () or contructor.newinstance (), the essence is the same, using the reflection mechanism.

Using deserialization

    /**
     * 5. Use deserialization */
    try (objectoutputstream oos = new ObjectOutputStream ("Book.dat");
        ObjectInputStream ois = new ObjectInputStream (New FileInputStream ("Book.dat"));) {
      oos.writeobject (BOOK1);

      Book Book5 = (book) ois.readobject ();
      System.out.println (BOOK5);

    } catch (IOException | ClassNotFoundException e) {
      //TODO auto-generated catch block
      e.printstacktrace ();
    }
 

Of course, in addition to the above several ways, you can also use JNI and other ways to create objects, this side is not enumerated.

The complete sample code is as follows:

Book.java

Package test;
Import java.io.Serializable;

Import java.util.List; /** * @author Wangmengjun * * */public class book implements Serializable, cloneable {private static final long Seri

  Alversionuid = -6212470156629515269l;

  /** Title */private String name;

  /** Author * * Private list<string> authors;

  /**isbn*/private String ISBN;

  /** prices/private float price; Public book () {}/** * @param name * @param authors * @param ISBN * @param price/public book (STR
    ing name, list<string> authors, String ISBN, float price) {this.name = name;
    this.authors = authors;
    THIS.ISBN = ISBN;
  This.price = Price;
  }/** * @return the name */public String GetName () {return name;
  }/** * @param name the name to set */public void SetName (String name) {this.name = name;
  }/** * @return The authors * * * public list<string> GetAuthors () {return authors; }/** * @param authors thE authors to set */public void setauthors (list<string> authors) {this.authors = authors;
  /** * @return The ISBN/Public String getisbn () {return ISBN;
  /** * @param ISBN the ISBN to set */public void Setisbn (String ISBN) {this.isbn = ISBN;
  /** * @return The price */public float GetPrice () {return price;
  /** * @param price "price" to set */public void Setprice (float price) {this.price = Price; }/* (non-javadoc) * @see java.lang.object#tostring () * * * @Override public String toString () {return "Boo"
  K [name= "+ name +", authors= "+ authors +", isbn= "+ ISBN +", price= "+ Price +"] ";
  @Override protected Object Clone () throws Clonenotsupportedexception {return (book) Super.clone ();

 }

}

Createobjectexample.java

Package test;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import java.lang.reflect.InvocationTargetException;
Import Java.util.Arrays;

Import java.util.List;
     /** * @author Wangmengjun * */public class Createobjectexample {public static void main (string[] args) {/** * 1.
    Create object using new/book Book1 = new book ();
    Book1.setname ("Redis");
    Book1.setauthors (Arrays.aslist ("Eric", "John"));
    Book1.setprice (59.00F);
    BOOK1.SETISBN ("abbbb-qq677868686-hsdkhfkhkh-2324234");

    System.out.println (BOOK1); /** * 2.
      Create object using Clone/try {book Book2 = (book) book1.clone ();
    System.out.println (BOOK2);
    catch (Clonenotsupportedexception e) {//TODO auto-generated catch block E.printstacktrace (); }/** * 3.
     Use Class.newinstance (); */try {book BOOK3 = (book) Class.forName ("Test.
      Book "). newinstance ();

      System.out.println (BOOK3);
      BOOK3 = Book.class.newInstance ();
    System.out.println (BOOK3); catch (Instantiationexception | illegalaccessexception |
    ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace (); }/** * 4.
     Use Constructor.newinstance ();
      */try {//Select the first constructor to create the book book Book4 = (book) Book.class.getConstructors () [0].newinstance ();

      Book [Name=null, Authors=null, Isbn=null, price=0.0] System.out.println (BOOK4); 
          /** * Invokes the specified constructor creation Object * * Book4 = (book) Book.class.getConstructor (String.class, List.class, String.class, Float.class). newinstance ("New Instance Example", Arrays.aslist ("Wang", "Eric"), "abc1111111-def-33333
      ", 60.00f); Book [Name=new Instance Example, Authors=[wang, Eric], isbn=abc1111111-def-33333, price=60.0] System.out.println (b
    OOK4); catch (Instantiationexception | Illegalaccessexception | IllegalArgumentException | InvocationTargetException | SecurityException |
    Nosuchmethodexception e) {//TODO auto-generated catch block E.printstacktrace (); }/** * 5.
        Use deserialization/try (objectoutputstream Oos = new ObjectOutputStream ("Book.dat"); ObjectInputStream ois = new ObjectInputStream (New FileInputStream ("Book.dat"));)

      {Oos.writeobject (BOOK1);
      Book Book5 = (book) ois.readobject ();

    System.out.println (BOOK5); catch (IOException |
    ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();

 }
  }

}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.