Skip to main content

Constructor in 5 mins




Q. What is constructor.

Constructor is a special member function which has same name as class name and called whenever the object of that class is created.


Q. What are the properties of constructor 

Constructor has following properties:

  • Constructor has same name as class name.
  • It is used for initializing variables of class.
  • It is called whenever object of class is created.
  • It does not have return type, not even void.
  • It can have parameters.


Q. How many types of Constructors are there.

  • Default Constructor       -->  public Message()
  • No-arg Constructor       -->  public Message()
  • Parametrized Constructor     -->  public Message(String str)
  • Copy Constructor                                



Q. What are rules for writing Constructor:


  • Constructor(s) of a class must has same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static and Synchronized.
  • Access modifiers can be used in constructor declaration to control its access 
  • It can have parameters
  • It should not contain return type.
  • It can have throws clause: we can throw exception from constructor.


Q. What happens if you keep a return type for a constructor?

It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name


Q. How to invoke constructor.

        Message m= new Message();


Q. What is the difference between constructors and other regular methods?



Constructor
Regular method
Constructors must have the same name as the class name and cannot return a value .

public class Message {

   
private String msg;   
   
//constructor
   
public Message() {}
//parameterize constructor
   
public Message(String str){
        this
.msg=str;
    }
}

The constructors are called only once per creation of an object.
Regular methods can have any name and can be
 called any number of times.

public class Message {
   
//Method
   
public String getMsg() {
    
System.out.println("hello method");
       
return "TestMethod";
    }
}

regular methods can be called many times.



Q. What happens if you do not provide a constructor?

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 constructor.

public Message() {}.


If a class includes one or more explicit constructors like


     //Non-parameterize or NO-ARG constructor
    public Message() {}

    //parameterize constructor
    public Message(String str){
        this.msg=str;
    }


Then java compiler does not create the default constructor public Message() {}.


Q. How a no – argument constructor is different from default Constructor?

By default compiler creates a default constructor with no formal parameters and no throws clause.

And If you have added your own constructor (no matter whether it's without parameters or with parameters) the compiler will not add the default constructor in this case.


Q. What is Constructor Chaining ?

Constructor Chaining is calling another constructor from one constructor.


Q. How you call one constructor from another? 

By using this() syntax.


package com.thread;

public class Message {

    // parameterize constructor
    public Message(String str) {
        System.out.println(str);
        System.out.println("String constructor");
    }

    // parameterize constructor
    public Message(Integer number) {
        // calling another constructor
        this("Calling String constructor");
        System.out.println("Integer constructor");
    }

    public static void main(String[] args) {
        Message m2 = new Message(3);
        Message m3 = new Message("Test");

        System.out.println(m2);
        System.out.println(m3);
    }

}

//Output
String constructor
Integer constructor
Test
String constructor


Q. How to call the superclass constructor?

You can use the keyword Super to invoke the super class’s constructor.

super("Your Text");


Q. Can we declare constructor as private?

Yes we can declare constructor as private.


Q. How to write  parameterize constructor? 


package com.thread;

public class Message {

    private String msg;
    private Integer number;

    // constructor
    public Message() {
        System.out.println("Empty constructor");
    }

    // parameterize constructor
    public Message(String str) {
        System.out.println("String constructor");
        this.msg = str;
    }

    // parameterize constructor
    public Message(Integer number) {
        System.out.println("Integer constructor");
        this.number = number;
    }

    public static void main(String[] args) {
        Message m1 = new Message();
        Message m2 = new Message(3);
        Message m3 = new Message("Test");

        System.out.println(m1);
        System.out.println(m2);
        System.out.println(m3);
    }

}
Output:
Empty constructor
Integer constructor
String constructor



Comments

Popular posts from this blog

Extent report plugin for cucumber framework

Extent Reports  are the most popular  reporting  used with Selenium. ExtentReport API makes our life easy to generate interactive  report  with simple configuartions. It supports almost all Java and .NET test frameworks such as TestNG , JUnit , NUnit etc Here we are discussing about  a plugin which is build on  Extent Report specially for Cucumber. This plugin is used to simple out the implementation of  Extent Report  in  Cucumber Framework .  We are creating a maven project to implement the integration of our plugin with cucumber 1. Create new maven project in any tool eclipse/sts/intellij 2. Open pom.xml and update below entries. Step 1 : Add Cucumber Extent Reporter library to Maven Project Add  cucumber-extentsreport <dependency>      <groupId> com.vimalselvam </groupId>      <artifactId> cucumber-extentsreport </artif...

java: You aren't using a compiler supported by lombok, so lombok will not work and has been disabled.

  In order to make projects compile with the existing builds of Lombok processor, as a workaround you can use the flag -Djps.track.ap.dependencies=false which should be added to File | Settings | Build, Execution, Deployment | Compiler | Build process VM options field. This will disable collection of dependencies specified by an annotation processor when Filer methods are called

Execution default of goal org.springframework.boot:spring-boot-maven-plugin:1.2.3.RELEASE:repackage failed: Unable to find main class

Solutions:  Solution 1 : You needed to change the packaging parameter to jar from pom. Also, the repositories , pluginRepositories , the maven-compiler-plugin and the spring-boot-maven-plugin's version and executions weren't needed. Solution 2:  Try mvn install and see if it works Solution 3: Preview: <properties> <!-- The main class to start by executing java -jar --> <start-class> com.mycorp.starter.HelloWorldApplication </start-class> </properties> Solution 4: Enable the main() method in your Application.java. Configure spring-boot-maven-plugin to specify the class with the main class (Spring should find it anyway if you have one, but good to be explicit): Preview: <plugin> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-maven-plugin </artifactId> <version> ${spring-boot-version} </version>...