There are two ways to create objects and two ways to create objects.

Source: Internet
Author: User

There are two ways to create objects and two ways to create objects.

It is often difficult to see the obvious difference between compiling and running using IDE, because development tools such as eclipse will automatically compile. When you create a class, it is compiled into a class file. After the modification is saved, the compilation is triggered again. So we can use NotePad to see what is called at runtime and try two ways to create an object.


First, let's look at an example with 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.

// Existing Apple public class Test {public static void main (String [] args) {Fruit f1 = new Apple (); f1.color ();}}

Perfect run:



// Use a non-existent pear class public class Test {public static void main (String [] args) {Fruit f2 = new Pear ();}}
An error is reported during compilation:


2. Use reflection to create objects.

// 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 Banana class does not exist only when it is detected during running, so an exception is thrown:



We can see that reflection does not compile classes one by one as needed (the following Banana is not compiled for US ):



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



We then use reflection to call a non-existent pear:

public class Test {public static void main(String[] args) {try {Fruit  f =  (Fruit) Class.forName("Pear").newInstance();f.color();} catch (Exception e) {e.printStackTrace();}}}

After the Test class is compiled, the system will find that the class file to be loaded does not exist at runtime:


It can be seen that reflection does not report errors during compilation, indicating that it is called at runtime. It assumes that all the related classes exist, so you need to capture exceptions that cannot be found.

Use the new object method to create an instance. The Compiler automatically compiles related classes for us as needed and loads these classes at runtime. The Compiler opens and checks related class files during compilation. For the reflection mechanism, the class file cannot be obtained during compilation, so the. class file is opened and checked at runtime.


Are there any questions:

What is the difference between a New object and a reflected newInstance?

Using new is a coherent action, loading the class and completing subsequent operations. When using newInstance (), you must ensure that the class has been loaded and the class has been linked (that is, the static domain is allocated with storage space, and if necessary, all references to other classes created by this class will be parsed ). Let's look at the trouble of separation, but we can get the benefit from it, that is, to make a fuss about Class. forName (), and it becomes more flexible here. We can create an interface and dynamically pass in the fully qualified name of the class implementing the interface. At this time, as long as there is its. class file, we can create its object. This greatly enhances the scalability of the program. For example, updating a software is usually the same principle. We must make long-term plans at the beginning and lay the groundwork. This method is widely used in the framework, because the framework must emphasize universality and scalability.

Therefore, the existence is reasonable and should be selected based on the actual situation.





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.