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.
Related
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!
is there any term call Virtual Constructor in Java?then where we need to use this?
Virtual Constructors are not a part of the Java language, but the term might be applied to some design patterns
For example, calling object.clone() on an object that supports it will produce a new object (much like new ClassName(object) if you have a copy constructor) and thus resembles a constructor, but is polymorphic. In "Effective Java" Joshua Bloch advocates the use of Static Factory methods as another way of achieving polymorphic object creation in certain circumstances.
For the use of the term in the C++ context look at: http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8
I'm not sure what you mean by "virtual constructor." Constructors are called recursively up the class hierarchy. Every constructor must call its super-class constructor as the first thing. (The call can be omitted if it is to the no-arg constructor, in which case the compiler will automatically insert it.)
As an aside, Java doesn't have virtual methods. Or, more precisely, every instance method is virtual (in the C++ sense).
What do you mean by virtual constructors? If it is like virtual function in C++ there is no virtual constructor in java.
Not that I'm aware off. "Default Constructor " yes. Delphi has virtual constructors, most other languages does not. See the Factory pattern for something related.
Depending on the definition of virtual constructor. If by virtual constructor, you mean static method that calls a private constructor as part of some factory patterns, then yes there are virtual constructors. I have found them very useful at times, when methods must be called on self after construction. All you have to do is simply set the constructor to private, and within the class, include a static method that creates the class object instance and returns it. This is useful when methods need to be called on the object before the user is able to use it. Since it is a very bad idea to refer to self in the constructor due to the fact that the object is not fully constructed, one can use a virtual constructor to call the methods after instantiation and before the user may have access to it.
I have few questions regarding Java constructors
Can a constructor be private? If yes then in which condition?
Is a constructor a method or not?
If a constructor does not return anything then why we are getting a new Object every time we call it?
What's the default access modifier of a constructor if we do not specify.
Edit
The answers for 1 & 3 are very clear. I'm still not sure about 2 & 4 since I'm getting different answers for them.
Can a constructor be private? If yes then in which condition?
Yes. There are no conditions. Of course, no one except the class itself can call it then.
This is actually a frequent pattern: Have a static getInstance() and keep the constructor private.
There can also be private constructors that the public constructors internally call.
Constructor is a method or not?
Hmm. I say "no". At the very least, it is a "very special kind of" method. In what context exactly? The terminology is less important than what you are trying to do.
If constructor does not return anything then why we are getting a new Object every time we call it.
The new operator returns something (the new instance).
Whats the default access modifier of a constructor.
Same as for methods. Package-private.
If you do not specify any constructor, the class gets a default constructor, which takes no arguments, does nothing except calling the parent constructor and is public.
Yes, in any case. However, if all constructors for a class are private, that means that the class cannot be directly instantiated. You will need to use something like the Factory Pattern to create instances of the object.
Yes, the constructor is a method.
A better way to think about it is that the new operator returns the object and in the process of creating the object, calls the constructor. Another way to think about it (although this is only a way to think about it, it isn't technically correct) is simply that the return type is implied by convention. A good place to read more about this is to read about new in the context of C++. The constructor's role is not to create the object but rather to initialize the memory contained within the object.
Default access for a constructor in Java is package private just like any other method. (One such source: http://www.javabeginner.com/learn-java/introduction-to-java-access-modifiers and from the horse's mouth: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
Yes, constructors can be private. This is done when you want tighter or alternate control over instance creation such as with factory methods or with a pattern such as a Singleton.
It is a method but it is not called directly. It is a special type of method invoked on your behalf when you create a new object.
Constructors don't return anything, they create new objects.
The default is package private. So public to any class within the package but not visible to code outside of the package.
Thoughts on Tomcat performance and scalability: This is a highly variable situation based on your server hardware and types of requests and of course the quality, efficiency and memory footprint of the code serving each request.
Your lower bound on concurrent requests was 500. Consider that you probably want to create a thread for each request and given a 1MB stack per thread you're looking .5 GB just for thread stack space. And this is before heap memory and the performance overhead of allocating that many threads. I think that if need to handle that many requests at a time you might want to consider a more heavy duty server like JBoss.
A constructor can be declared private for any class.
A constructor is a special method that returns an instance of the class it belongs to, therefore you do not need to specify a constructors return type.
Package private is the right answer as pointed out below.
Yes -- factory instance singletons often use this pattern, to force users to init their class via static factory method.
Yes, it's a method
Because that is what a constructor does - it constructs. (it's assumed the result of construction will be returned)
same as methods
With regards to your Tomcat question, it depends on which version of Tomcat, which IO model it's using (e.g., NIO versus historical network IO modules), and your configuration. Single Tomcat's can process hundreds of requests at a time, although the concurrency is tune-able (each request will be handled by a distinct thread or thread from a pool).
The default access modifier of a constructor is CLASS ACCESS MODIFIER,
If a class is public , then access modifier of a constructor is public. If the class is default , then constructor is also default.
Constructor can be created as a private in any case.
Constructor is a special type of method which can be automatically called when we
are creating object for the corresponding class.
Constructor does not contain any return values. It just create new objects. Should not provide any return type for constructor.
The default access specifier of the constructor is public
Yes.
Yes.
because a constructor is called by new. What returns the object is the new, the constructor simply sets up the internal state.
Public.
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.
In Java, for each object, a new copy of instance variables is created which can be accessed using the object reference.
But in case of an instance method, only one copy of it(instance method) exists.
How is this method accessed by various object references?
The byte code (or native code if it's JIT'd) for the method is stored in one location. When the method is called, a pointer (under the hood, aka reference at a higher level) to the instance object is passed as the first argument so the method code can operate on that specific instance - have access to its fields, etc. In order to save space without additional performance cost, the calling mechanism in Java is quite a bit more complicated than C++, especially for interface methods.
Methods and fields are completely different. Methods apply to all instances of the object, but fields are per instance.
One way to think of it:
pretend the method is "global" to all instances, but it is "passed" an instance of the object via the "this" reference.
Methods can change the state of a particular instance, but they themselves are stateless.
Behind the scenes a reference to the object is passed to the method as part of the call. It may be useful to look at Java's reflection classes, Method.invoke() in particular.
From a previous answer of mine:
I'm sure the actual implementation is quite different, but let me explain my notion of method dispatch, which models observed behavior accurately.
Pretend that each class has a hash table that maps method signatures (name and parameter types) to an actual chunk of code to implement the method. When the virtual machine attempts to invoke a method on an instance, it gets the object's class, and looks up the requested signature in the class's table. If a method body is found, it is invoked, providing the original object as a reference called this.
Otherwise, the parent class of the class is obtained, and the lookup is repeated there. This proceeds until the method is found, or there are no more parent classes—which results in a NoSuchMethodError.
If a super class and a sub class both have an entry in their tables for the same method signature, the sub class's version is encountered first, and the super class's version is never used—this is an "override".
the implied reference "this" is passed in to each method, which of course you can reference explicitly
I'm assuming you're meaning on a simplistic level, as in how you actually do the call.
I'm also assuming you're refering to a method that has the static modifier in its signature, ie:
public static int getNum()
{
// code in here
return num;
}
If this is what you mean, and this was part of a class called 'SomeClass', then it would be accessed via the method call SomeClass.getNum(). ie, you put the actual class name before the method.
If this is not what you mean, ignore my answer :)