On two ways of creating objects

Source: Internet
Author: User
Tags pear

Often using the IDE is not easy to see the obvious difference between compiling and running, because development tools like eclipse are compiled automatically. When you create a class, you compile it into a class file, and the changes you make on that basis will trigger a compilation once it is saved. So we can use Notepad to see what a runtime call is, to experience two ways to create an object.


Let's start with an example that has the following interfaces and two implementation classes:

Public interface Fruit {public void color (); public class Apple implements Fruit {@Overridepublic void color () {System.out.println ("red");}} public class Banana implements Fruit {@Overridepublic void color () {System.out.println ("Yello");}}

1. Use new to create an object.

The existing Apple class public class Test {public static void main (string[] args) {Fruit f1 = new Apple (); F1.color ();}}

Perfect operation:



Use a non-existent Pear class public class Test {public static void main (string[] args) {Fruit F2 = new Pear ();}}
Error during compilation:


2. Use reflection to create an object.

The existing Banana class public class Test {public static void main (string[] args) {try {Fruit F =  (Fruit) class.forname ("Banana"). Newinstance (); F.color ();} catch (Exception e) {e.printstacktrace ();}}}

The runtime discovers that the Banana class does not exist , so throws an exception:



By looking at the reflected reflection, the class is not compiled as needed ( The following Banana does not compile for us ):



At this point we compile the Banana class manually and then run Test:



We then use reflection to invoke the nonexistent pear:

public class Test {public static void main (string[] args) {try {Fruit  f =  (Fruit) class.forname ("Pear"). Newinstan CE (); F.color ();} catch (Exception e) {e.printstacktrace ();}}}

The same Test class compiles , and the runtime discovers that the class file to be loaded does not exist:


As you can see , using reflection does not make an error during the compile phase, indicating that it is a runtime call. It assumes that all related classes are present, so you need to catch exceptions that cannot be found for the class.

Using The method of the new object to create the instance , the compiler automatically compiles the relevant classes for us as needed, and loads the classes at run time , and the compiler opens and examines the relevant class file at compile time . For the reflection mechanism,theclass file is not available at compile time, so open and check the . class file at run time.


Whether there is a question here:

What is the difference between a New object and a newinstance () using reflection ?

Using new is a coherent action that loads the class and completes the subsequent operations. When using newinstance (), you must ensure that the class is loaded and that the class is already linked (that is, allocating storage space for the static domain and, if necessary, parsing all references to other classes created by the class). Although separate the obvious trouble, we can get the benefit, that is in Class.forName () on the fuss, here becomes more flexible. We can create an interface and then dynamically pass in the fully qualified name of the class that implements the interface, at which point the. class file can create its object. The scalability of this program is greatly enhanced. For example, if we update a software that is usually the principle, we must start with a long-term plan and bury the foreshadowing. This approach is more widely used in the framework, as the framework inevitably emphasizes versatility and extensibility.

Therefore, the existence is reasonable, when using the actual to choose.





On two ways of creating objects

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.