31/12/2019

What is Constructor in Java :Studywow

 Studywow topics are: what is constructor in java or what are constructor in java.

Q1. What are constructor in Java? What are its properties?

 Or What is constructor? How are they different from number function? Explain with example?

Ans. Constructor: Constructor in Java is a special type of method that is used to initialise the object. Every class has a constructor. Constructor has following properties :
    1. same name of the class to which it belongs.
    2. invoked at the time of object creation.
    3. no explicit return type.
    4. cannot be inherited, through a derived class.
    5. can be made private.
    6. can pass arguments.
Syntax: access NameofClass (parameters) {
initialisation code
}
The constructor is different from number function in the following ways:

1. Object :-

Constructor: It is used to initialise the state of an object.
Number Function: It is used to expose behaviour of an object.

2. Return type :-

Constructor: It must not have return type.
Number Function: It must have return type.

3. Invoked by :-

Constructor: It is invoked implicitly.
Number Function: It is invoked explicitly.

4.  Constructor :-

Constructor: The Java compiler provides a default constructor if you don't have any constructor.
Number Function: It does not provide constructor.

5. Class Name :-

Constructor: It must have same name as class name.
Number Function: Method name may or may not be same as the class name.

6. Syntax :-

Constructor: public NameofClass
(parameters) {
initialisation code }
Number Function: public static int funcName
(Parameters) {
// body  }

7. Example :-

Constructor: public class Studywow {
public Studywow ( ) {
}
public Studywow (String name) {
} }
Number Function: public static int min
Function (int n1, int n2)
{
int min;
if (int n1 > int n2)
min = n2;
else min = n1;
return min;
}

Q2. Difference between Default Constructor and Parameterised Constructor?

Ans. 1. Default constructor :-
(i) Used to initialise object with same data.
(ii) Contains no parameter.
(iii) When data is not passed at the time of creating an object, default constructor is called.

2. Parameterised Constructor :-

(i) Used to initialise each object with different data.
(i) It have parameters.
(iii) When data is passed at the time of creating an object, default constructor is called.


Studywow: What is Constructor in Java. Read more topics of Java on studywow to click here.


Join us on Facebook and Twitter  to get the latest study material. You can also ask us any questions.
Facebook = @ studywow
(click on it or search "studywow" on facebook)
Twitter = @ studywow
(click on it or search "studywow" on Twitter)
Email= studywow.com@gmail.com
Send us your query anytime!