In this article, we are going to talk about class Constructors and how to use constructor, Constructor is just a special method that has the same name as the class and it doesn't have a return type. A java file can contain multiple classes but only one class can be public, If you notice how our first created class is public, The other classes that you'll create in this file will not be public, For now, we will create a class inside the same file to make it easier to follow later we will use more files and more classes, Constructors are mainly used to initialize instance variables, They're called whenever we create a new instance of our class, You can look at classes as building blocks or blueprints from which we create instances in memory, The new operator is used to create a new instance and with a new instance, we can then call some methods. So first let's create our class "Dog" for example
COMPLETE CODES:
Above public class Main we are going to create another class like "class Dog{}" And now we can specify some attributes or some private variables like private String color; this will represent the color of our dog Now we need to add constructor because the constructor is used to initializing instance variable and this "color" is instance variable of dog, So let's create constructor like "public Dog(String color){}" if you notice how it doesn't have a return type and now we can specify parameters like '(String color)' So this is a parameter that we assign to our caller private variable if we try to type color = color; that will be actually great alt, So why is it great Alt? Well we are assigning variable to the same variable, Notice if you click on "color argument" it will highlights both colors, When you click on "private String color" variable it doesn't highlight anything, So the 'color = color' will not work, If we want to specify our variable color that is part of the dog class, we need to use the keyword 'this' like this.color = color, (this) keyword is used to call methods or to call variable and assign them when we have the same parameter as the same variables or in other words when we have the same name, so our parameter has the name color and our field also has the same name color, thus we need to find a difference between them and there is "this" keyword that is used for finding that difference, Now when we type this.color = color; notice when I click on the "color" on the right side it highlights the argument when I Click the left side 'color' it will highlight our private fields. We can add some methods, but first let's see the error we can get when we create constructors, for example, we create another constructor like 'public dog(){}' This will not compile because this doesn't match the name of the class, notice how the name is different it has a capital letter "D" so the error will be that we can't call the 'method declaration' it is invalid method declaration, we didn't specify return type. Now if you try to create a constructor for example 'public void Dog(){}' The name matches but constructors don't have a return type if you specify a return type java will say that this is a method and not a constructor so you need to be careful with return type using the constructor. We can add some methods to our class Dog, These methods don't need to be static we will explain static method later, so public void printColor(){} this will print the color value to our console, for example, we want a print color with System.out.println("color =" +this.color); But here in the method 'printColor()' we don't have an argument that has the same name as a variable so the keyword ('this') so 'this' keyword is optional and we can remove it and it will still refer to our field. Let's create a few instance of dog-like 'Dog dog = new Dog("gray"); then we can call method like 'dog.printColor();
now the method is an instance method of instance 'dog', We can create another Dog dog2 = new Dog("black"), And now we have two instances of our Dog class in memory, We can then call a method in 'dog2' like 'dog2.printColor();' let's run the code and see the output. Through constructor we are just passing arguments and constructor initializes the fields inside the class to our arguments, it just basically assigns the values to fields and we should see it prints color = gray, color = black. Let's see another example where we can chain constructor, first let's create class 'Cat'
class Cat{
private String name;
private int age;
}
example our class Cat will have two different variables like private String name, and private int age; and now we can have a constructor without any arguments for example 'public Cat(){}' it can be empty for now we will assign some default values, but since we want to assign some default values to 'name' and 'age', in this way we can type name = "Tom"; age = 3; And now when we call Cat constructor without arguments name and age will be initialized to this values, but we can add another constructor 'public Cat(String name, int age){} ' in this case we need to initialize our variables like 'this.name = name' and 'this.age = age' if you notice that we have now the same arguments name and fields name and that is why we need to use (this) keyword. But if you notice how we have sort of duplicated codes in the first constructor we are saying name = "Tom", age = 3; and in the second constructor we are basically assigning some values for those two fields. Instead of duplicating the code, We can just call the second constructor from the first constructor and pass some default values. to call the second constructor there is a 'this("Tom", 3)' and now this line will call the second constructor and the second constructor initialize 'this' variables with our default value ("Tom", 3) so that is called chaining constructor that is when you chain one after another, when we click on 'this' keyword you will notice how it highlights the second constructor, in this way we can follow which constructor class another constructor in case there are for example 4 - 5 constructors. And now we can also add some methods to our 'Cat class' for example
'public void printInfo()'{
System.out.println("name =" +name+"age="+ age);
}
this method will just print name and age, And now in our main method we will create two instances of 'Cat' and we were print those values. The first instance will be called the 'Cat' without any arguments like Cat cat = new Cat(); then a cat.printInfo(); When we call the constructor without arguments we're calling the first constructor and the first constructor calls our second constructor and initializes values to ("Tom", 3). If we create another Cat cat2 = new Cat("Jerry", 5); Now we're only calling the second constructor and then we can print cat2.printInfo(); if we run our code you will notice how first it will print name = Tom, age = 3 because that was initialized to name and age by calling our constructor without arguments and that constructor call the second constructor, while the second constructor just initializes those variables. the second line will be name = Jerry, age = 5.
0 Comments