Constructors Basic

Constructors Basic

   They are instructions for  making objects. So, if you make a new object the program at that point stops and goes to the the constructor, which runs until the constructor is finished and then returns  to the point right after where the object was made. A constructor makes a object by taking the parameters it is given and setting the fields equal to those parameters. A constructor always has the same name as it’s class by the way.

In java they give you a constructor known as a no-args constructor which takes no parameters and doesn’t set any fields to anything, in other words it does nothing, but make a object. It disappears if you make a constructor of your own though.

The format for creating a object is:

    ClassName ObjectName = new ClassName(<parameter>);

A constructor is formatted in:

public( private) ClassName(<parameters>)

{

   Field =parameter;

}

So a good example would be say we had a class called Square which makes a Square, the constructor would be something like:

Public class Square     // declaring class

{

 public int side;           // field representing side length

 public Square(int s)  //declaring constructor

 {

     side=s;               //setting field equal to parameter

 }
}                              //ending class

You would create a new object of this class like shown below:

Square mySquare = new Square(4);

Which would make a square with a side length of 4.

A link to a video I made explaining the topic is shown below:https://youtu.be/-Gv19VP1kIg