Steps involved in instantiation of Class? - java

When we write a statement like Foo f = new Foo(); we know that JVM calls the Defaut ClassLoader.loadClass(), which return instance of Class , now how do we get our Foo instance from Class ?

I'm not entirely sure what you're asking, but if you're asking what code is executed when you create a new instance of a class, then the answer is that this is a primitive operation of the Java virtual machine, and there isn't any Java code involved.
The behaviour of instance creation is specified by the section 12.5. Creation of New Class Instances of the Java Language Specification.
There is also a section on 4.10.2.4. Instance Initialization Methods and Newly Created Objects in the Java Virtual Machine Specification, but that's not all that interesting.
To find out what actually happens when you create an object, you would need to choose a JVM implementation and read its source code. Alternatively, you might do what most Java programmers do, and think of it as an essentially magical operation that just works!

Related

Just started learning Java. Why is the main() inside of a class?

I'm learning Java and I noticed that the main() is put inside of a class. Why? I don't consider my main() to be a member of any object. So please tell me how I can get around this.
I don't consider my main() to be a member of any object.
It's not since it's a static method. It does not belong to any object but to the class itself.
Aside from that, all methods, including main must be defined in classes.
More generally, a class is the smallest unit in compiled Java code and contains both information on instances of the class and behavioral code that runs by itself (e.g. the main method).
By nature, Java is highly object oriented. So everything must be encapsulated within a class. All methods must be placed inside of a class. However, the main() is different. There can only be one main function in a class and it must always be static, meaning it is not part of an object and there is only one instance of it. When a java application is executed, the JRE will look for the main class (i.e. the class containing the main function). main() is where the execution starts. But due to the very nature of OO, it must be placed in a class. You can say that this is simply because of the skeletal structure of java. No other reason in particular.
You must put the main() in a class. And, it must be static (which means it is not a member of any Object). When you launch the Java Runtime Environment (JRE) it will load that class and invoke the main().
This is covered by JLS-12.1 - Java Virtual Machine Startup which says in part,
The Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings. In the examples in this specification, this first class is typically called Test.

early binding late binding is it same as runtime and compile time?

When we create object inside a function is that object created at runtime?
What are the things happen? created? at compile time and at runtime?
Is early binding and late binding also means compile time and runtime?
What is dynamic linking static linking? is it right to think compile time when I hear static? damn I so confused?
sorry guys I know my english is bad and also please make your answers and examples beginner friendly as possible.
Early binding is like going getting tomatoes from the refridgerator and putting them on the table before you starting cooking the soup.
Late binding is starting cooking the soup, and when you need tomatoes, then you go to get them from the refridgerator.
Cooking the soup is run time.
Getting the knife,spoon and saucepan ready is compile time. (It doesn't involve tomatoes.)
Ok here's a pseudo coded explanation :
late binding :
... get :
if (myvar is null) myvar = new object;
return myvar
early binding
myvar = new object;
... get :
return myvar
When we create object inside a function is that object created at
runtime?
What are the things happen? created? at compile time and at runtime?
That depends on what you mean by "object." If you mean a class instance, then yes it will be created at runtime on either the stack or the heap. Statically allocated objects, like strings or types explicitly declared as static, will be created at compile-time in the data segment. Static variables live for the life of the program.
Is early binding and late binding also means compile time and runtime?
From Wikipedia:
With early binding the compiler statically verifies that there are one
or more methods with the appropriate method name and signature. This
is usually stored in the compiled program as an offset in a virtual
method table ("v-table") and is very efficient. With late binding the
compiler does not have enough information to verify the method even
exists, let alone bind to its particular slot on the v-table. Instead
the method is looked up by name at runtime.
In a nutshell, in early binding the compiler looks up the method and its offset in the symbol table, so that information must be available, whereas in late binding that can't be done, and the runtime must look it up. Note that late binding is very different from dynamic dispatch, though they are often used synonymously, in that the latter refers to using a dispatch table or "vtable" to store pointers to a method's implementation, which may be overridden.
What is dynamic linking static linking?
Basically this is difference between including referenced files or "libraries" in the final executable (static) and placing them into the program image at runtime. Obviously, the former adds unnecessary size to the executable, but (1) you never have to worry about dependency issues and (2) program start up is more efficient. On the other hand, dynamic linking (1) saves spaces and (2) allows library updates to occur in one place.
Nothing in Java is statically linked, but it is statically bound. "Static" means the compiler identifies the exact description of the function to be called: class name, method name, argument types. It does NOT determine its address in memory. That's the difference between static binding and static linking, and this means that it is still not known at compile time what code will be executed when you call a static method. It depends on what's in the .class file that the JVM loads at runtime. Java statically binds all calls to static methods -- hence the keyword. It also applies static binding to private methods, since they cannot be overridden. A similar argument applies to final methods.
Dynamic binding means that the compiler decides everything like in the static case, except for the class which contains that method. The exact class is determined at the last moment before calling the method, relative to the object on which the method is being called. Object.equals is such a dynamically bound method. This means that the same line of code can call a different method each time it is executed.
Early binding == static binding; late binding == dynamic binding. These are synonyms.
early binding is a assignment of value to design time where a late binding is a assignment of value to runtime
There is only difference between run time and design time it must show the value of assignment .
For example:
//early binding
myvar =new myvar();
// get
retutn myvar

Is this the way Constructor in Java allocates memory?

Default constructor is automatically called after an object is created.
But in Java when we allocate memory using new operator i.e. classname obj = new classname(); the constructor is automatically invoked before new allocates memory to the class member's.
The allocation starts after the class comes into physical existence but if new operator completes its process after default constructor is called, then how default constructor actually do so as the class has not come into physical existence?
Can someone explain me the same using a clear example?
The process is basically:
Memory is allocated
Execution goes up the constructor chain (i.e. all the this / super calls to other constructors) each level evaluating any arguments to the level above, but that's all
Execution goes down the constructor chain for the actual constructor bodies. So the body of the java.lang.Object constructor is executed first, then the direct subclass, etc. This is also when variable initializers are executed. (Prior to this, the variables have their default values of null etc.)
The reference is returned to whoever called new
The idea of a default constructor has no meaning at execution time. It's just a parameterless constructor which calls super() as far as the JVM is concerned.
The business about the constructor chain is exactly the same as it would be if these were methods with a first line which just chains to the next constructor along; it's just a stack of calls.
But in Java when we allocate memory using new operator i.e. classname obj=new classname(); the constructor is automatically invoked before new allocates memory to the class member's.
That is incorrect. The constructor is invoked after memory has been allocated.
#Jon Skeet's answer explains clearly the sequence of events that occur during object creation.
You may be confused by the fact that the constructors may well cause further objects to be allocated; e.g. during the execution of the declaration initializers. But these objects don't occupy memory in the original object; i.e. the object we are constructing.
If you want a definitive specification of what happens when an object is created, read the Java Language Specification - in particular JLS 12.5.
If we consider an example like
classname obj = new classname();
classname obj initialize the object and new classname(); allocates memory location for the object. If you have a constructor, then the constructor is called, otherwise default constructor is called.
Default constructor is automatically called after an object is created.
Yes (if the default (no-argument) constructor was called).
Can someone explain me the same using a clear example.
I'm not sure I understand your question to 100 % but no where in the Java Language Specification it says that the constructor should run it's code before the memory for the object has been allocated.
This is explained in great detail with an example in Section 12.5: Creation of new Class Instances in the Java Language Specification.
"...then how default constructor actually do so as the class has not come into physical existence. "
The class is already in memory, the new operator allocates memory space to hold the instance variables and parents instance variables specific to the new instance. But the class had come into physical existence before.

why MyClass.class exists in java and MyField.field isn't?

Let's say I have:
class A {
Integer b;
void c() {}
}
Why does Java have this syntax: A.class, and doesn't have a syntax like this: b.field, c.method?
Is there any use that is so common for class literals?
The A.class syntax looks like a field access, but in fact it is a result of a special syntax rule in a context where normal field access is simply not allowed; i.e. where A is a class name.
Here is what the grammar in the JLS says:
Primary:
ParExpression
NonWildcardTypeArguments (
ExplicitGenericInvocationSuffix | this Arguments)
this [Arguments]
super SuperSuffix
Literal
new Creator
Identifier { . Identifier }[ IdentifierSuffix]
BasicType {[]} .class
void.class
Note that there is no equivalent syntax for field or method.
(Aside: The grammar allows b.field, but the JLS states that b.field means the contents of a field named "field" ... and it is a compilation error if no such field exists. Ditto for c.method, with the addition that a field c must exist. So neither of these constructs mean what you want them to mean ... )
Why does this limitation exist? Well, I guess because the Java language designers did not see the need to clutter up the language syntax / semantics to support convenient access to the Field and Method objects. (See * below for some of the problems of changing Java to allow what you want.)
Java reflection is not designed to be easy to use. In Java, it is best practice use static typing where possible. It is more efficient, and less fragile. Limit your use of reflection to the few cases where static typing simply won't work.
This may irk you if you are used to programming to a language where everything is dynamic. But you are better off not fighting it.
Is there any use that is so common for class literals?
I guess, the main reason they supported this for classes is that it avoids programs calling Class.forName("some horrible string") each time you need to do something reflectively. You could call it a compromise / small concession to usability for reflection.
I guess the other reason is that the <type>.class syntax didn't break anything, because class was already a keyword. (IIRC, the syntax was added in Java 1.1.)
* If the language designers tried to retrofit support for this kind of thing there would be all sorts of problems:
The changes would introduce ambiguities into the language, making compilation and other parser-dependent tasks harder.
The changes would undoubtedly break existing code, whether or not method and field were turned into keywords.
You cannot treat b.field as an implicit object attribute, because it doesn't apply to objects. Rather b.field would need to apply to field / attribute identifiers. But unless we make field a reserved word, we have the anomalous situation that you can create a field called field but you cannot refer to it in Java sourcecode.
For c.method, there is the problem that there can be multiple visible methods called c. A second issue that if there is a field called c and a method called c, then c.method could be a reference to an field called method on the object referred to by the c field.
I take it you want this info for logging and such. It is most unfortunate that such information is not available although the compiler has full access to such information.
One with a little creativity you can get the information using reflection. I can't provide any examples for asthere are little requirements to follow and I'm not in the mood to completely waste my time :)
I'm not sure if I fully understand your question. You are being unclear in what you mean by A.class syntax. You can use the reflections API to get the class from a given object by:
A a = new A()
Class c = a.getClass()
or
Class c = A.class;
Then do some things using c.
The reflections API is mostly used for debugging tools, since Java has support for polymorphism, you can always know the actual Class of an object at runtime, so the reflections API was developed to help debug problems (sub-class given, when super-class behavior is expected, etc.).
The reason there is no b.field or c.method, is because they have no meaning and no functional purpose in Java. You cannot create a reference to a method, and a field cannot change its type at runtime, these things are set at compile-time. Java is a very rigid language, without much in the way of runtime-flexibility (unless you use dynamic class loading, but even then you need some information on the loaded objects). If you have come from a flexible language like Ruby or Javascript, then you might find Java a little controlling for your tastes.
However, having the compiler help you figure our potential problems in your code is very helpful.
In java, Not everything is an object.
You can have
A a = new A()
Class cls = a.getClass()
or directly from the class
A.class
With this you get the object for the class.
With reflection you can get methods and fields but this gets complicated. Since not everything is an object. This is not a language like Scala or Ruby where everything is an object.
Reflection tutorial : http://download.oracle.com/javase/tutorial/reflect/index.html
BTW: You did not specify the public/private/protected , so by default your things are declared package private. This is package level protected access http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

What is the main difference in object creation between Java and C++?

I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?"
I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when constructor of one class calls a method of another class which isn't constructed yet and so on, but I can't find anything obvious. The answer is supposed to be one or two sentences, so I don't think that description of whole object creation process in Java is what they had in mind.
Any ideas?
What is the main difference in object creation between Java and C++?
Unlike Java, in C++ objects can also be created on the stack.
For example in C++ you can write
Class obj; //object created on the stack
In Java you can write
Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object
In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):
In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)
What?
Let's imagine a Base class, with a virtual method foo().
Let's imagine a Derived class, inheriting from Base, who overrides the method foo()
The difference between C++ and Java is:
In Java, calling foo() from the Base class constructor will call Derived.foo()
In C++, calling foo() from the Base class constructor will call Base.foo()
Why?
The "bugs" for each languages are different:
In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.
Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.
Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml
In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.
During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.
Scott Meyers, http://www.artima.com/cppsource/nevercall.html
Besides heap/stack issues I'd say: C++ constructors have initialization lists while Java uses assignment. See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for details.
I would answer: C++ allows creating an object everywhere: on the heap, stack, member. Java forces you allocate objects on the heap, always.
In Java, the Java Virtual Machine (JVM) that executes Java code has to might1 log all objects being created (or references to them to be exact) so that the memory allocated for them can later be freed automatically by garbage collection when objects are not referenced any more.
EDIT: I'm not sure whether this can be attributed to object creation in the strict sense but it surely happens somewhen between creation and assignment to a variable, even without an explicit assignment (when you create an object without assigning it, the JVM has to auto-release it some time after that as there are no more references).
In C++, only objects created on the stack are released automatically (when they get out of scope) unless you use some mechanism that handles this for you.
1: Depending on the JVM's implementation.
There is one main design difference between constructors in C++ and Java. Other differences follow from this design decision.
The main difference is that the JVM first initializes all members to zero, before starting to execute any constructor. In C++, member initialization is part of the constructor.
The result is that during execution of a base class constructor, in C++ the members of the derived class haven't been initialized yet! In Java, they have been zero-initialized.
Hence the rule, which is explained in paercebal's answer, that virtual calls called from a constructor cannot descend into a derived class. Otherwise uninitialized members could be accessed.
Assuming that c++ uses alloc() when the new call is made, then that might be what they are
looking for. (I do not know C++, so here I can be very wrong)
Java's memory model allocates a chunk of memory when it needs it, and for each new it uses of
this pre-allocated area. This means that a new in java is just setting a pointer to a
memory segment and moving the free pointer while a new in C++ (granted it uses malloc in the background)
will result in a system call.
This makes objects cheaper to create in Java than languages using malloc;
at least when there is no initialization ocuring.
In short - creating objects in Java is cheap - don't worry about it unless you create loads of them.

Categories

Resources