fbpx
Coding Basics JAVA programming

Constructors In Java For Beginners

constructors in java

So, today we learn about Constructors which are very useful in java programming language.

What are Constructors?

Constructors have automatically initialized the objects when they are created. Once you define your own constructor, the default constructor is no longer used.

So, it has the same name as the class in which it resides and is syntactically similar to a method. Once we defined the constructor, it’s automatically called when the object is created, before the new operator completes it.

The constructor is also a class type so we do not use return type in the constructor. But most constructors will not display anything. They simply initialize an object.

Code:

public class Hello {
String name;
//Constructor
Hello(){
	this.name = "developersnation.co.in";
	}
public static void main(String[] args) {
	Hello obj = new Hello();
	System.out.println(obj.name);
	}
}

Output:

developersnation.co.in

Tip: If you implement any constructor then you no longer receive a default constructor from Java compiler.

Question:

What is true about constructor?

Correct! Wrong!

The constructor returns a new object with variables defined as in the class. Instance variables are newly created and only one copy of static variables is created.

Share This Post To Your Friends

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *