Skip to main content

Posts

Showing posts with the label Constructor

Are Java Constructors Inherited ? If Not, Why Not?

You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's super classes. One of the main reasons is because you probably don't want to override the constructor of super class', which would be possible if they were inherited. By giving the developer the ability to override a super class constructor you would erode the main feature of encapsulation abilities of the java programming language.

What happens when an object is created in Java?

Everyone knows Java is an object oriented programming la nguage. Ev ery object in java is a reference to a real entity. So whenever you create an object of class ma ny things will happened in JVM. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its super classes. Implementation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values.   The constructor for the most derived class is invoked. The first thing the constructor does is call the constructor for its uppercase. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variables will be initialize d and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes ...

When to use "private" constructor?

-- The private constructors are used in the following situation: When you implement singletons or factory design pattern. Do not want people to instantiate your class directly. e.g., new MyObject();. For example, all of your method and fields are static, you may need to add a private default constructor (if you do not have it, compiler will add one for you that is not what you want). Such way can enforce that people can not accidently use "new".

What happens if you do not provide a constructor?

Java does not actually require an explicit constructor in the class description. If you do not include a constructor, the Java compiler will create a default constructor in the byte code with an empty argument. This default constructor is equivalent to the explicit "Pet(){}". If a class includes one or more explicit constructors like "public Pet(int id)" or "Pet(){}" etc, the java compiler does not create the default constructor "Pet(){}".