Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

What is the purpose of a constructor in Java? What is the difference between these two code snippets:

public class Program 

{

 public constructor ()

 {

 function();

 }

 private void function ()

 {

 //do stuff

 }

 public static void main(String[] args) 

{

 constructor a = new constructor();

 } }

And 

public class Program {    

    public static void main(String[] args) {

        function();

    }        

    private void function() {

        //do stuff

    }

}

1 Answer

0 votes
by (13.1k points)

A constructor is something that is used to initialize the instances of classes. Using a constructor you can create new objects often with parameters specifying the initial state or other important information about the object.

The difference between the two codes is in the first code you thought you are writing a constructor method but in actuality what you did is you created an object from a method with no return type. A constructor name must be the class name. 

In the second code, you created a static reference to the non-static method function() which would throw an error and it does not have a constructor defined by you but the JVM will assign a default constructor to it.

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
asked Feb 20, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 23, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
asked Feb 16, 2021 in Java by Jake (7k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...