Instantiate an Object

To instantiate an Object ,you either use an import statement or Class.forName() method ,both actually creates a runtime class
objects .But where ,when can I use import statement &  a Class.forName()  What is the real purpose of this two ways of creating a runtime class objects?
RajinikanthAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

BeatachonCommented:
hi rajnikanth, the import statement
does not instantiate any objects. Its purpose in life is to state which packages are to be used in the class.

The Class.forName() can be used to instantiate an object, as can the "new" keyword.

As for which on of those you chose, the "new" keyword is what you use 99.9% of the time.

-ben
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

JodCommented:
Where can you use import statement?

Import statements are the very first lines of your code when writing a class. If you are using any classes or methods that someone else has written in your code, then import tells the compile which ones they are and where to find them.

So if you want to use a JPanel you need to import:

import javax.swing.JPanel;

or you can import everything in the same package like this:

import javax.swing.*;

Packages are how code is organised in Java - each package is like a category of classes which are similar in some way.



What is the difference between new and Class.forName()?

For instantiating objects the difference between when you use new and when you use Class.forName is for instantiating objects at runtime or compile time.

What does this mean? Well...

when you write some code you may know that you need to store some text. This text can always be stored as a string so you can say in your code:

String s = new String("my string");

To do this though, you need to know when writing the code and before it is compiled all the types of objects you will be using before hand.

As you write more complicated code (such as using database access or reading data from a file) you may find that you are not sure what type of objects you are dealing with until you actually read them in.

The simplest example, is you can write a simple program that asks the user for a class name and if it can find it will instantiate it. If it can't it will give an error:


public class makeclasstest {

  public static void main(String args[]) {

    String s = args[0];

    // if user gave a string as a parameter try to instantiate it as a class
    if (s.length() > 0) {
   
      // show which class we are trying to instantiate
      System.out.println("Trying to instantiate class " + s);

      try {

        // try to create the new class object on the fly...
        Class c = Class.forName( s.trim() );

        // make a new object of this type...
        Object o = c.newInstance();
     
        System.out.println("It worked - instantiated a new object of type " + c.getName() );
        System.out.flush();

      } catch (Exception e) {
        System.out.println("Instantiation failed for class " + s);
        System.out.println("Error was " + e);
      }
    }
   
  }
}  

Save this code as makeclasstest.java and compile it.

When you run the code give it a class name as a parameter, such as:

java makeclasstest makeclasstest

and it will work make a new object of type makeclasstest.

Now try:

java makeclasstest java.lang.String

and so on. You will need to use fully qualified class names such as java.lang.String and some classes will not work as newInstance only works for classes with constructors with no parameters - you need to extend the code further to make it handle other classes.

But this is just a simple example so don't sweat it...the important thing is that you can see how this is a neat way of making classes on the fly and something you cannot do with new.


0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RajinikanthAuthor Commented:
Hi Beatchon,

Thanks for your response

Then what is the real purpose of Class.forName()?
0
mbormannCommented:
>>>>>Then what is the real purpose of Class.forName()?

Jod explained it already,

For instantiating objects the difference between when you use new and when you use Class.forName is for instantiating objects at compile time or runtime .

he just interchanged the words 'compile time' and 'runtime'.
People like Beatchon just come in and barge ,hoping to get undeserved points ,i do hope u would be giving it to him.
0
_lychee_Commented:
just 2 comments... :)

newInstance won't work for classes with no null constructors...

as for barging, i once saw an answer posted later than a comment which was essentially a renaming of variables in the prev comment, and it was accepted! can u believe that?? duh....
0
JodCommented:
>> newInstance won't work for classes with no null constructors...

Sounds like what I wrote above:

"...You will need to use fully qualified class names such as java.lang.String and some classes will not work as newInstance only works for classes with constructors with no parameters - you need to extend the code further to make it handle other classes..."

Ohhhhh, the irony of it...:-)
0
_lychee_Commented:
oops sorry... din see that :)

?irony?
0
JodCommented:
Just as you were saying about people repeating comments...to quote:

"...as in Oedipus Rex , where Oedipus prays for the discovery and punishment of the city's polluter, little knowing that it is himself..." = irony.

Don't worry, happens to us all...


0
_lychee_Commented:
well... i wasn't trying to barge; that's the reason for my first sentence (just 2 comments)
0
mbormannCommented:
Jod,
u a literature buff too?Ah'm not matey but i do love poems and classic old rock.
0
JodCommented:
_lychee_ , I know, just joking...
0
JodCommented:
Rajinikanth:

Back to the point now anyway, does this all make sense toyou now?
0
RajinikanthAuthor Commented:
Hi Jod,
 
You have solved my problem regarding instantiate of an Object,having explained it nicely .Thanks for your response
I accept your comment as answer
0
JodCommented:
If you want to know more about this subject then have a snoop through this:

http://codeguru.developer.com/java/tij/tij0119.shtml

which tells you in a rather lengthy fashion all about instantiation of objects at run time.

Cheers...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Delphi

From novice to tech pro — start learning today.