java constructors
java constructors
Constructors are an important part of learning Java effectively. So, let’s kick-off this
comprehensive guide to Java constructors with the rules pertaining to the creation of
a Java constructor:
The Java Default Constructor has no parameters. This is why it is also known as a
no-arg constructor. The general syntax of a Java default constructor is:
<class_name>(){}
Example:
class ConstructorDemo
Output:
Example:
class ParaConst
{int id;
String name;
ParaConst(int i, String n)
id = i;
name = n;
s1.display();
s2.display();
Output:
The Java compiler differentiates between the overloaded constructors by the total
number of parameters in the list and their types. Following code snippet
demonstrates constructor overloading in Java:
class OverloadConst{
int id;
OverloadConst(int i,String n)
id = i;
name = n;
id = i;
name = n;
age = a;
s1.display();
s2.display();
}}
O
Constructor vs. Method in Java
A Java method is a piece of code that has some specific name. It can be invoked
during any point in the program by simply using the method name. It can also be
understood as a subprogram that operates on data and returns some value.
The Java constructor is a special type of method. Both are similar in many ways, but
not identical. Here are some of the most important differences between a Java
constructor and a Java method:
Other than using a constructor for copying values from one object to another, the
same can also be accomplished by:
Or
Following program demonstrates using a Java constructor for copying values from
one Java object to the other:
class Copy
{int id;
String name;
Copy(int i,String n)
id = i;
name = n;
Copy(Copy s)
id = s.id;
name = s.name;
s1.display();
s2.display();
}
Output:
• Calling a method
• Object creation
• Starting a thread
Q: What will happen if you add a return type for a Java constructor?
A: A Java constructor with a return type will be treated as a typical Java method
along with the Java compiler generating a “this method has a constructor name”
warning.
Summary
So, that was all about the Java constructor. Learning how to effectively use
constructors is among the important bits for building sound know-how of the high-
level, general-purpose programming language.
Source : https://hackr.io/blog/java-constructor