Constructor
Constructor is a special Member function whose task is to initialize the object of its class is called Constructor.
- Constructor is a block which is similar to method
- Constructor is special because its name is the same as the class name
- Constructor is invoked whenever an object of its associated class is created.
#Example :
public class object {
object(){
System.out.println("Constructor called");
}
public static void main(String[] args) {
object sc = new object();
}
}
# Note points:
1.Modifier applicable: 1.Public
2.Protected
3.default
4.private.
2.It not necessary to write a constructor for a class it is
because the Java compiler create constructor(no. argument)
if your class doesn't have any.
3.Private constructor used in restricted object creation.
4.Constructor doesn't have any return type.
5.It execute automatically when we create object
i. object sc = new object();
ii.new object();
6.When a class contain a constructor it is guaranted that an
object created by the class will be initialized automatically.
7.When a constructor is declared for class then initialisation
of the class object become mandatory.
# Need :
- Object initialization
- Overloading
- default (compiler initialize)
- no-argument (user-define)
- parameterized constructor
- default constructor : Created by the compiler itself when the programmer doesn't create any constructor. The default constructor has no arguments and has an empty body.
public MyClass()
{
// This is the default constructor
}
- no-argument (user-define) constructor : A no-argument constructor in Java is a constructor that takes no arguments. A no-argument constructor in Java also know as user-define constructor.
Syntax :
public MyClass()
{
// statements / operations;
}
- parameterized constructor : A parameterized constructor in Java is a constructor that takes arguments. parameterized constructor can contain one or more arguments.
Syntax :
public MyClass(arguments)
{
// statements / operations;
}
Comments
Post a Comment