Explan various types of constructors in Java

https://www.computersprofessor.com/2016/06/explan-various-types-of-constructors-in.html
|
||||||||||||||||||||||||||||
Ex:-
class Sample
{
int m;
int n;
Sample()
{
m=0;
n=0;
}
When a class contains a
constructor like the one defined above. It is guaranteed that an object
created by the class will be initialized automatically. For example, the
declaration.
Sample x = new Sample()
Not only creates the
object x of type sample but also initializes its data members m and n to
zero.
|
||||||||||||||||||||||||||||
1.
Default constructor: -
A constructor that accepts no parameters is called the default constructor
for class A is A::A() If no such constructor is defined, then the compiler
supplies a default constructor. Therefore a statement such as:
A a;
2.
Parameterized Constructors: - It may be necessary to initialize the various data
elements of different objects with different values when they are created.
Java permits us to achieve his objective by passing arguments to the
constructor function when the objects are created. The constructors that can take
arguments are called parameterized constructors.
class Sample
{
int m;
int n;
Sample(int x, int y)
{
m=x;
n=y;
}
}
Sample x =new Sample(10,20);
|
||||||||||||||||||||||||||||
Multiple
constructors in a class: - Java permits us to number of constructors in the same
class. For example, could define a class as follows:
class Sample
{
int m;
int n;
Sample()
{
m=0;
n=0;
}
Sample(int a, int b)
{
m=a;
n=b;
}
Sample(Sample ob)
{
m=ob.m;
n=ob.n;
}
}
This declares three
constructors for a sample object. The 1St constructor receives no
arguments, the second receives 2 integer arguments and the third receives one
sample class object as argument. For example, the declaration
Sample x = new Sample();
Sample x = new Sample(10,20);
Sample x = new Sample(sample ob);
|
||||||||||||||||||||||||||||
Subclass
Constructor: -
A subclass constructor is used to construct the instance variables of both
the subclass and the super class. The subclass constructor uses keyword super
to invoke the constructor method of the super class The keyword supper is
used subject to the following conditions.
·
Super
may only be used within a subclass constructor method.
· The
call to super class constructor must appear as the 1St statement
within the sub class constructor.
· The
parameters in the super call must match the order and type of the instance
variable declared in the super class.
|