Java Constructors and initializing class variables - java

In Java, does the constructor of a class create an instance of that class? And if it does, does it also initialize the variables of that class?

Constructor doesn’t create the instance of the Class.
Instance creation is done using either:
1.Using Class.forName()
2.ClassLoader loadClass()
3.Using clone()
4.Deserialization
5.Using reflection
6.new keyword
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1.Constructor name must be same as its class name
2.Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1.Default constructor (no-arg constructor)
2.Parameterized constructor

Constructors don't create objects. They merely initialize objects(and their data members) once they are created using parameters(when provided) or to default values.

When you create an instance of the class using new operator, the constructor of the class is called so as to initialize the instance variables.
If the constructor defined is default, then instance variables have to be assigned to the newly created object explicitly.
However when you override a constructor using fields, then the instance variables for that newly created object are assigned during object creation.

I would love to explain this in a very simple language. In the real-world to build something, we need two things first is its prototype/model, and the second is someone who can create it based on that prototype.
A very relevant simple example is to build a house, you first need its blueprint(map), then a constructor who can build it based on that blueprint. So, similarly in the programming language
Object: A real-world entity for which we create a class.
Class: A class describes the "blueprint" of the objects that are made out of it (are instances of it).
For software development, we first have to think about the objects(any real-world entity), then we create a class (blueprint) for it, which contains its attributes.
After creating a class when we need to create one or more objects based on it, for this, we need a constructor to build it.
Whenever we create a new object, we have to use new keyword, and it tells the constructor to create the object.
When you are initialing variables in a class they are just part of the blueprint, based on that, the object will be created. So, without a constructor, you cannot create new objects, but there are some exceptional cases and tricks where you can create them without calling constructors.

Related

Can a Java constructor return already existing object of same type?

Whenever we call a constructor in Java, it creates a new object and returns its reference in the end (of newly created object).
Is there any possibility that a Java constructor does not create a new object but return the reference to an already created object?
// Is it possible that myObject is not a new object, its already existing object
MyClass myObject = new MyClass();
I have a list of objects of some class, and based on few parameters in constructor sometimes it more efficient that I don't create a new object, instead I pick up an already existing object. Is there is any other way?
No. Constructors by definition run when a new object is created to initialize it. If the constructor is run, a new object has already come into existence, and there's nothing you can do about it.
What you could do is make a static method which either creates a new object, or returns an existing one. This is the standard approach in such cases.
Say, Boolean.valueOf(boolean value) in the standard library exists for the purpose of avoiding creation of extra objects. You can create them using new Boolean(value), but it is much better to call this method because it will return the same object for the same values.
you cannot do this using constructors but you could use one of the patterns mentioned below.
If you only ever need 1 object then use the Singleton pattern.
If your might have a few variations then use Flyweight pattern as duffymo mentioned.
As duffymo mentions in his comment below - if you using any of these patterns then its important from a concurrency perspective to understand that these objects will be global state - you should therefore ensure they are immutable, and if you cannot make them immutable then you may want to rethink your approach.
No, this is not possible.
JLS section 15.9:
Unqualified class instance creation expressions begin with the keyword new.
An unqualified class instance creation expression may be used to create an instance of a class, regardless of whether the class is a top level (§7.6), member (§8.5, §9.5), local (§14.3), or anonymous class (§15.9.5).
and JLS section 12.5:
A new class instance is explicitly created when evaluation of a class instance creation expression (§15.9) causes a class to be instantiated.
...
Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure: [...]
Notice that this clearly mentions creation of objects and not a possibe re-utilization.
On the other hand, you could create a static factory for your object that uses a pool. You could take a look at the implementation of Integer.valueOf(i) for example. Refer to this answer for example.
You cannot achieve this with just a constructor in Java.
If required, such a behaviour is achieved by using either static method inside the class (like Integer.valueOf(0)) or the whole dedicated object of the different class (like DocumentBuilderFactory) to return the instances. This provides enough control to substitute the existing object instead of always creating a new one.
As a rule, such objects should be immutable and thread safe to be easily shareable. Also, instance reuse and sometimes caching is implemented along these lines.
No. Class provides the blueprint for objects, when using the new operator it is followed by a call to a constructor, which initializes new object.
Source.
If you wish to reuse objects for any reasons you may want considering implement the Flyweight pattern as well as the Factory pattern into your project for best result.
No it's not possible. Create a static method to create objects based on required logic and don't forget to make constructor private.

Does a superclass instance also being created when creating a subclass instance?

I have seen many threads (e.g.: Inheritance in Java - creating an object of the subclass invokes also the constructor of the superclass. Why exactly?) saying that the instance of superclass will NOT be created when creating a subclass instance. I actually agree with this opinion.
However, I can't find any official materials (from Oracle) to back this up. I searched a couple of hours and cannot find anything. Can anyone refer me to a reliable resource to confirm this?
When you create a new instance and the class constructor is called, enough memory is being reserved in the heap for that instance's attributes to be stored. Those attributes comprise both:
Attributes directly belonging to your class definition;
Attributes belonging to all upper nodes in your class hierarchy tree.
Yes, the superclass constructor is called, but with the sole purpose to initialize attributes of the superclass. It never means a new object of the superclass will be created.
Check these links, they may help you to understand the process:
http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html
http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
On the second link, documentation states: It is new which creates the object. That is: It reserves memory for all the class references (Object attributes) and primitive values.
Then, the constructor is called, and its aim is to initialize enclosing class' attributes.
Since the object attributes are references in Java, the constructor may use new to create object attributes, their references will be the values stored in your object's memory.
The superclass constructor just continues this task for your class inherited attributes.
When an instance of a derived class is created the heap allocation will be something like (*):
Standard JVM object header (with pointer to Class object for DerivedClass)
Instance fields for class Object
Instance fields for class BaseClass
Instance fields for class DerivedClass
So in effect, if you ignore the DerivedClass instance fields the object looks remarkably like an instance of BaseClass, and the JVM can reference the object as if it were an instance of BaseClass and have no difficulty doing so.
Similarly, in the Class object for DerivedClass is a "virtual method table" with:
Virtual method pointers for Object
Virtual method pointers for BaseClass
Virtual method pointers for DerivedClass
The JVM makes virtual calls by indexing into this table to find a specific method, knowing that, say, hashValue is method number 5 and printTheGroceryList is method number 23. The number needed to call a method is determined when a class is loaded and cached in the method reference data in calling classes, so calling a method is: Get the number, go the the Class object pointed to by the instance header, index into the virtual method table, pull out the pointer, and branch to the method.
But when you look closely you will see, eg, that the pointer in the Object group that points to the hashValue method actually points to the one in BaseClass (if BaseClass overrides hashValue). So the JVM can treat the object as if it were an Object, invoke hashValue, and seamlessly get the method in BaseClass (or DerivedClass, if it also overrides the method).
(*) In practice the instance fields may be intermingled to a degree, since "aligning" fields from a superclass may leave gaps in the heap allocation that fields from a subclass can fill. This is simply a trick to minimize object size.
Base Class's object is not instantiated when a Derived Class's object is instantiated. Inheritance only brings certain attributes and methods of Base Class to Derived Class. Constructors/destructor of base class are called along with those of derived class when object of derived class is made/destroyed. But this does not mean object of base class is also made.
An object is identified by its address, stored in variables of object types. the new operator returns that address, and only one address, so there can only be one object. You can check this by looking at System.identityHashCode(this) in sub- and superclass constructor, for example.

What is constructor in java, if it is not a member of class?

What do we we call a constructor, if it is not a member of a class as stated in Oracle doc: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
I think the term "member" was defined to exclude constructors for the sake of convenience. Constructors, even public ones, are not inherited; members are inherited (unless they are static and/or private). It would be awkward when talking about the rules of inheritance to always have to say "members except constructors".
From the Java Language Specification, §8.2:
Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
Just call constructors "constructors".
Its a special method that every class has, which is called after creation of the object. in JVM its called using invokespecial so, lets just call it a special method?
And since there is just 1 special method in Java - they all call it "constructor"
All the doc is saying is that the constructor is not inherited by default. Since the constructor is a method that is invoked on the construction of the object in the memory heap, then once you create a subclass that inherits from a super class, the constructor of the super class is not invoked by default.
For instance if you have a class Vehicle and a subclass Car, assume the Vehicle constructor is as follows:
public Vehicle(String vehName) {
this.vehName = vehName;
}
Then, even though your class Car inherits from class Vehicle, the vehName member (field) will not be set as the constructor above does.
So you will need to do something like this:
public Car(String vehName) {
super(vehName);
}
Hope that helps
In Java, a class body (the area between braces) can contain the following key items: (1) Fields (2) Methods (3) Other Classes (nested classes) (4) Constructors (5) Initializers
An object created from a particular class shall take the shape that is similar to the blueprint (class) from which it's created. Now, if you look at items that can be contained in a class body, only item (1) to (3) help in determining what sort of object can be created from a particular class definition.
Constructors and initializers only play part in actual creation of the object (e.g. initialization of already defined fields), but do not determine what shape/state that object shall carry, and what behaviors it will display.
For this reason, to me, it make sense to call item (1) to (3) class members (i.e. class members are those items within a class body that determine how an object created from the class looks like and behave); whereas constructors and initializers are not members because their absence in a class definition does not affect a class state and behavior.
As such, only class members can be inherited as the whole point behind inheritance is to enable a subclass reuse state and behavior of its superclass.
A Constructor is a method which is in a class which is used to create a new instance of that class.
Being a member of a class just means that the item in question is in the class.
Constructor is a method which name is same as the class. It is used to initialize the object of class. It's implicit in action. Parametric constructor initialize object with different value.

Instance Vs Object

When we have base and sub class in java, and we instantiate the sub class, we get one instance or two instances? If we get two objects, how many instances we get? Does one instance holds the two objects of base and sub class or two separate instances?
If you instantiate a subclass, you will get just one object/instance. This single instance will contain all of the fields of the subclass (which includes the fields defined by its parent classes).
Remember that subclasses means that you're defining a new class which derives from an existing parent, that is it inherits those definitions. So if the parent declares a field called id, the subclass will also have a field called id, and so an instantiation of that subclass will contain an id field. This field is declared in the parent class, but it does belong to the subclass.
If you instantiate the subclass, there is no instantiation of the parent. No object exists whose runtime class is the parent class.
(I'm not sure what your distinction is between "object" and "instance" in your question. You've used them in a way that implies they are different, but typically they mean exactly the same thing. An object is an instance of a particular class.)
You get a single instance that is of the two classes - the base and the subclass.
Try to understand it with this example: there is a class Mammal and the class Human. You belong to both of them - nevertheless, there is a single instance of yourself. If there were two persons in the room, you would have two instances of both classes!
Instance == object ... both are the same, just 2 different names. If you create one object (maybe a subclass) you get one object.
When we have base and sub class in java, and we instantiate the sub
class, we get one instance or two instances?
We get one instance because each Java class instance is contained in a single object.
If we get two objects, how many instances we get?
The term "instance" is synonymous to object. Saying one instance is just a different way of saying one object.
Does one instance holds the two objects of base and sub class or two
separate instances?
No. Java compiler creates class bytecode that contains the functionality of both base and extension, so instantiating that class results in a single object.
What is then the logical difference between instance and object?
In the context that you are using these words, there is no difference. An instance (of a class) is an object, and vice-versa.
However, in the broader context, an instance (of a type) is not necessarily an object - it depends on the type. For instance that you could say that 42 is an "instance" of the int type.
new classA(); //Here you create an instance of a class
classA ob //create object named "ob" and datatype "classA"
And now we assign the instance to the object
classA ob = new classA();
like
int num = 10

Can I redefine a method / constructor using reflection in Java?

I have a class called A and I need to create a new object of that class without calling its constructor. I want to set all its attributes through reflection.
Can I redefine the constructor of class A using reflection?
Or is there any way other way to do this?
In the Sun/Oracle JVm you can use Unsafe.allocateInstance(Class). Otherwise you have to generate byte code to create the instance without calling a constructor. You could use ASM for this. You cannot create an instance without a constructor using Reflection alone.
BTW: You can define a new method using byte code manipulation, but to add a constructor, you have to change the class before it is loaded. (This is tricky to do)
Invoke the object with the constructor that takes the least amount of arguments; using dummy arguments. Then proceed to manipulate the object however you like.

Categories