Concept of Constructor Overloading
Constructor Overloading
Like
methods, constructors can be overloaded. In other words, you can provide more
than one constructor for a class if each constructor has a unique signature. Constructors with the same name as that of the Class name and has a different (number or Datatype) of parameters differ from each other is simply known as constructor overloading. If you have a class name 'Student' then the Eg of Constructor overloading in Student class be like:
public Student(String first,
String last, double mark)
{
firstName = first;
lastName = last;
Mark = mark;
}
public Student(String first, String last,){
firstName = first;
lastName = last;
}
public Student(int rollNo, String last,){
RollNo= rollNo;
lastName = last;
}
public Student(double mark){
Mark = mark;
}
The previous example has four constructors with the same name as that of its class name 'Student' but they contain different no of parameter list and different Datatypes from each other. and hence It defines the Constructor Overloading.
Default Constructor
If
you do not provide a constructor for a class, Java will automatically create
a default constructor that has no parameters and doesn’t
initialize any fields. This default constructor is called if you specify
the new keyword without passing parameters. For example:
Ball b = new Ball();
Here,
a variable of type Ball is created by using the default constructor
for the Ball class.
If
you explicitly declare any constructors for a class, Java does not create
a default constructor for the class. As a result, if you declare a constructor
that accepts parameters and still, want to have an empty constructor (with no
parameters and nobody), you must explicitly declare an empty constructor for
the class.
Great, thanks for sharing this post.Much thanks again. Awesome.
ReplyDeletenet coure
net training