Saturday, May 7, 2016

Constructors


A constructor is a special method that runs every time you create an instance of a class. Constructors unlike regular methods do not need a return type. The name of the constructor always has to be the same of the class you make it in. When you make an instance of a class it will run the constructor. A common use for a constructor is initialization of instance variables. For example if you have a class called dog, and an instance variable “name”. So you want to make objects of that class, where all the dogs’ names are the same. A constructor allows you to make each object have that name, without declaring each name individually to each class. All you have to do is make a new object with the constructor that declares the name. Another useful thing you can do with constructors is call other constructors. The way you call or access a constructor is by using the key word “this()”, where you put your parameters for the constructor your calling in the parenthesis.

No comments:

Post a Comment