Pages

What is Constructor

What is Constructor?
  • Constructor is special concept in every OOP language which is used to initialize values for the data members.
  • Constructors are automatically invoked whenever object or Instance for a class is created.
  • Constructor name should be same as className
  • Constructor should not have any return type.
  • Syntax: className(){ //block of code }
    
    
    Basically we have 2 types of constructors:
    1. Default constructor - Constructor having No arguments
    2. Parameterized Constructor - Constructor having arguments
    Constructor
    Constructor
    Demo on Default Constructor:
    public class DemoConstructor {
        String Bank;
        String Name;
        int Mobile;
    DemoConstructor() { // Default constructor
            System.out.println("This is constructor Block");
            Bank = "SBI";
            Name = "personName";
            Mobile = 1234567890;
        }
    
        public void accountType() {
            System.out.println("Print statement");
        }
        public static void main(String args[]) {
            DemoConstructor dc = new DemoConstructor(); //constructor automatically invoked
            System.out.println(dc.Bank);
            System.out.println(dc.Name);
            System.out.println(dc.Mobile);
            dc.accountType();
        }
    }
    --> Here, Whenever object created constructor is automatically invoked.
    --> But accountType() is a method which will be called explicitly by using object.
    Output:
    This is constructor Block
    SBI 
    personName
    1234567890 
    Print statement

    • Java compiler provides a default constructor if we don't provide any constructor in a class.
    Constructor
    Constructor
    Please comment below to feedback or ask questions.

    No comments:

    Post a Comment

    Please comment below to feedback or ask questions.