Ad Code

Constructor, Arguments,Getter and Setter

Define

    why we take Constructor?
    what is benefit of constructor?
    why we pass the argument in constructor?
    why we take getter and setter function?


Constructor is a special function of class. It is not the same but something similar like function. Constructor is a function which call automatically at the time of execution of program. The name of a constructor is same as the name of the class. Constructor can take parameter also, Constructor containing parameter are called parametrized constructor.
Constructor is called or created at the time of object creation. There are different types of constructor like default constructor, parametrized constructor, copy constructor.
Default constructor:
It is a constructor which is called when we don’t make any constructor in a program. The compiler by default call this constructor if he do not found any constructor in a program.
Parametrized constructor:
The constructor which contains parameter is called parametrized constructor.
Copy constructor:
A copy constructor for a class is a constructor that has an object of the class as its only parameter. It makes a new object that is a duplicate of the original object.
Constructor overloading:
Constructor overloading is same as the function overloading . you have to pass different argument to the parameter of a constructor at the time of execution i.e.. at the run time. Compiler matches the argument with constructor and call according to that.

Getters and Setters allow you to effectively protect your data. This is a technique used greatly when creating classes. For each variable, a get method will return its value and a set method will set the value.

You may ask why you shouldn't just edit the value directly. The reason for this is twofold. Firstly, if you decide that some action should be taken every time you change the value of a particular variable, you only need to edit the set method instead of looking for every place you change the variable. Another reason is that a person using your code can look for all methods starting with get or set instead of looking for specific variables that they need to remember.
Reactions

Post a Comment

0 Comments