Originally posted by sandeep vijan:
i was asked in an interview to give difference between class
instantiation and object instantiation?
i never thought them to be different and answered just this.
but to my surprise they said these two are different things.
i later tried to read ooad with apps(Booch) and found that
it also hinted at a similar thought, but unfortunately
that book is tough to understand and also it is more
focussed on c++ and discusses such things with c++ in
mind.
so at the end i only know that is some difference between
those two terms, but what it is, is still not known/clear.
i would like to take this oppurtunity to ask author
Jacquie Barker(this is a question of java objects).
hoping for an answer from anyone and everyone.
Hmmm ... this sounds like fuzzy terminology to me. The term "instantiation" as I've always used it means "to create an instance/object based on a class definition/template". I have not heard of "object instantiation" as being different from "class instantiation". The only thing I can guess at is that perhaps when they say "class instantiation", they are referring to the point in time at which a class is first loaded into the Java Virtual Machine (?). That is, when you type
java MyProgram
at the command line, then the class loader loads the byte code contained in MyProgram.class into the JVM. (The JVM is also preloaded with all of the classes in the java.lang package.) Then, whenever your program first references a class by name -- say, Person -- then the JVM loads that class's byte code into the JVM.
Just as we write constructors that are used to control how an object is instantiated, there is also a technique that we can use for running code that is to be executed only once, when the class is loaded into the JVM.
Here's a simple example to illustrate this concept (sorry about the fact that the indentation is messed up):
public class Example {
int x;
// A static code block gets invoked only once, when
// a class is first loaded into the JVM.
// You can think of it as a
// "constructor" for the class as a whole!
static {
System.out.println("Loading the Example class ...");
}
// A "normal" constructor for (instances of) OBJECTS
// of type Example.
public Example() {
x = 1;
System.out.println("Instantiating an Example object ...");
}
public static void main(
String[] args) {
Example a = new Example();
Example b = new Example();
Example c = new Example();
}
}
Compile and run this program, and you'll see the following output:
Loading the Example class ...
Instantiating an Example object ...
Instantiating an Example object ...
Instantiating an Example object ...
So, perhaps when they talk about class instantiation, this is what they are referring to ... ?
------------------
author of:
Beginning Java Objects