JAVA Theory
Constructors:
1. Special member function to initialize the objects of its class.
2. Its name is same as the class name.
3. It is invoked whenever the object is created.
4. It construct the values of data members of the class so it is named as the constructor.
Class Integer |
---|
{ int m,n; public: integer();//constructor declared ...... }; |
Characteristics of Constructors:
-
1. They should be declared in the public section.
2. They are called automatically when the object are created.
3. They do not have return type even void.
4. They have same name as the class name.
5. They can have default arguments as the other function.
Types of JAVA Constructors
There are two types of constructors:
Default Constructor:
A constructor that no parameter is known as default constructor.
Syntax |
---|
<class_name>(){} public class Bike { Bike() { System.out.println("Bike is created"); } public static void main(String args[]) { Bike b=new Bike(); } } |
Parameterized Constructor:
A constructor that have parameters is known as parameterized constructor.
Syntax |
---|
class Student { String studentName; int studentAge; //constructor Student(String name, int age) { studentName = name; studentAge = age; } void display() { System.out.println(studentName+ " "+studentAge); } public static void main(String args[]) { Student myObj = new Student("Teju" , 15); myObj.display(); } } |