Default constructor and with parameters: what they are, what they are for and how to use

Have you noticed that in the last tutorial on how to declare and create class and instantiate objects, we did: 
Student student = new Student (); 

You noticed how repeated 'Student' twice? 
Why? It is pointless or a waste of time to repeat it? 

In Java - indeed, in programming - everything has a reason. 

In this article you will learn about the constructors and know the reason for the repetition and how to use the methods constructors.


The explanations and examples in this tutorial are based on other articles in this section: 
What are Classes and Objects in Java 
How to create a class and declare an Object 
Accessing and modifying variables Classes and Objects 


What are method constructors in Java


When we use the keyword 'new' to create an object of a certain class, we are allocating a memory space. By doing so, Java requires that some variables are initiated with some value. 
This act start act, is made by the constructor, which are methods - we will study further in our online course Java soon. 

The Java automatically initializes the global variables when creating an object of a class. 
In the last article of our course, we made an example with the class "Student", where we create three variables: "name", "mathGrade" and "physGrade" that are considered global variables of the class, they are not part of any method. 

Therefore, they must be initialized by Java. For you see how this actually happens, look in your main class, which contains the 'main', and after the creation of the object "neil" from class "student", add the following lines of code to print, so you can see how these variables of the class already have a value, without even anything have assigned: 
Student neil = new Student(); 
System.out.println (neil.nome); 
System.out.println neil.notaMat); 
System.out.println (neil.notaFis); 

The result is: 
null 
0.0 
0.0 

That is, by default, strings are initialized with values ​​'null' (null) values ​​and zeros for numbers. 
This is what happens automatically when no constructor is specified. We will show how to specify constructors. 


What is and how to use the default constructor in classes


Constructor is a method in Java. 
Although we have not studied methods also, we will tell you how to use. It's pretty simple, and you will soon learn all about our method in Java Progressive course. 

Methods are a piece of code that make a specific thing in programming. If you have studied C or C + +, there they are called functions, routines or subroutines in other languages, such as Perl. 

We can create multiple constructors. The standard constructor is the one that takes no parameters. 
In simplest terms, is one that does not receive any information. He will always run when you create an object. 

To create a constructor, create a method with the same name as the class. 
Methods has the following syntax: 
methodName (parameterType parameterName) { 
 // Code of our methods 
} 

As our class is called "Student", our method is a constructor of this class and it is the default (takes no parameters) and is 'public', it will look like this: 
public Student() { 
} 

To better visualize the usefulness of the default constructor, we add a print: 

public Student() { 
System.out.println ("Object created"); 
} 

When you run your program, you will see the message "Object created" is displayed after you have created the object "neil". 
This method is called the default constructor. Contrary to what many think, default is not standard (although we use a lot as it were). 
Default is missing. When we are omitting other constructors - receiving parameter - is the default constructor the to be called. 

Note that when you create the object, use "new Student();" - so do not pass any parameters. So clearly we call the default constructor. 


Creating a constructor that takes parameters


In our application to register a student, the Class has a variable name and two grades, we are assigning the values ​​of these variables in direct object: 
neil.name = input.nextLine(); 
neil.mathGrade =  input.nextDouble(); 
neil.physGrade = input.nextDouble(); 

What we do now, to illustrate how constructor who receive parameters works, is asking that data before create tthe object, and start "neil" with these data. 
For example, let's create the variable "Name", "mathGrade", "physGrade" in the 'main', receiving these data for the Scanner: 
name = input.nextLin(); 
mathGrade = input.nextDouble();
physGrade = input.nextDouble(); 

Now let's create our constructor in class "Student" who receives these three parameters: a string and two doubles. 
It will look like this: 
public Student(String Name, double MathGrade, double PhysGrade){
        name = Name;
        mathGrade = MathGrade;
        physGrade = PhysGrade;
}


This may seem a little strange or complicated now, but when studying better methods, make all sense of the world and you will see how simple it is. 
What this method does is get a string "Name", two doubles "MathGrade" and "PhysGrade" and assign them the values to the variables of the Student class. 

See our class has a string variable "Name" and two doubles "mathGrade" and "physGrade" which would be initialized to 'null' and '0 .0 ', as shown earlier in this tutorial. 
What we are doing with this construct method is to initialize these variables with other values! And what are these values? Now, are the values ​​of the variables "Name" and MathGrade" and "PhysGrade", which we define as the Scanner class in method 'main'. 

Although we are beginning on object orientation concepts, let's do something interesting and show how powerful and useful this technique is. Let's add a variable in the class, a double named "averae" and int the constructor we will add a line of code: 
average = (mathGrade +  physGrade)/2; 

So, our constructor will be: 

public Aluno(String Name, double MathGrade, double PhysGrade){
        name = Nome;
        mathGrade = MathGrade;
        physGrade = PhysGrade;
     
        average = (physGrade + mathGrade)/2;
}


What does it mean? 
That when we begin our object with the grades, this method will automatically calculate the average of these grades! 
You may think "But I could did it in the 'main' during the print's, It's not the same thing?". 
Imagine that you will fill in the details of 20 students. 

So will put this formula 20 times? Of course not. 
This is where lies the beauty of Classes & Objects. You represent that formula once, and can use it whenever you create an object! 
Created the object, it began with the variables, it will automatically calculate the average! 
To access this variable just do: neil.average 
And she'll be there, cute for you to use. 


How instantiate Objects with parameters/arguments


Now we create our default constructors and methods with parameters, we show how to start an object with these data. 

In the default constructor, we've been doing: 
Student neil = new Student(); 

Now that we have the variables "Name", "MathGrade" and "PhysGrade" and a constructor who is prepared to receive these three types of data, we can create an object and throw these variables this way: 
Student neil = new Student(Name, MathGradePhysGrade); 

Note that you should only create this object after these variables with the correct values, or you will start the object with wrong values. 

An important detail is that the name of these variables, "Name", "MathGrade" and "PhysGrade" do not need be equal to those that declare there in the class constructor "Student". We could say: 
Student neil = new Student(name, math, phys); 

Since "name" is a string and "math" and "phys" doubles, it's Ok. When they 'arrive' in the constructor, they 'get' under the names "Name", "MathGrade" and "PhysGrade". 
You will get used to it when studying methods. 


Classes with more than one construct


What happens if we let the default constructor: void Student() 
and the constructor with parameters: public Student (String Name, double MathGrade, double PhysGrade) 
together in class "Student"? 

Nothing. Indeed, it is even recommended. It's a great costume. 
If you start an object of this class with no parameters, the method starts the Java default constructor (which displays the message "Object created". 
If you start an object with 3 parameters, it assigns these intervals you went to the values ​​of the object and still averages. 
You can also create other methods, they receive only the student's name, just math or just physics grade. 

Anyway, the constructors are made to initialize the object attributes and prepare for use, whatever use you want to give. If you use multiple constructors, Java is smart enough to know which method to use depending on the parameters you pass. 
Obviously if you create two constructors with the same parameter list, will have problems. 

To show an example of using two constructors - the standard and receives 3 parameters - we will create two objects, "geddy" early on, and we will see the message "Object created". 
Then ask the student data and initialize the object "neil" with parameters. We then use the variables of the object that student, including their average, which was calculated by the constructor. 

Here's the code: 

FirstClass.java
import java.util.Scanner;
        
public class FirstClass {

    public static void main(String[] args) {
        Student geddy = new Student();
        String name;
        double mathGrade,
               physGrade;
        
        Scanner input = new Scanner (System.in);
        
        System.out.print("Student's name: ");
        name = input.nextLine();
        
        System.out.print("Math grade: ");
        mathGrade = input.nextDouble();
        
        System.out.print("Physics grade: ");
        physGrade = input.nextDouble();
        
        Student neil = new Student(name, mathGrade, physGrade);
        System.out.printf("The students \"%s\" take %2.2f in Math, "
                + "%2.2f in Physics, so his average grade is %2.2f\n", neil.name,
                                                            neil.mathGrade,
                                                            neil.physGrade,
                                                            neil.average);
    }
}



Student.java
public class Student {
    public String name;
    public double mathGrade,
                  physGrade,
                  average;
   
    public Student(){
        System.out.println("Object created");
    }
   
    public Student(String Name, double MathGrade, double PhysGrade){
        name = Name;
        mathGrade = MathGrade;
        physGrade = PhysGrade;
       
        average= (mathGrade + physGrade)/2;
    }
}

No comments: