JavaRush /Java Blog /Random EN /Introduction to classes: writing your own classes, constr...

Introduction to classes: writing your own classes, constructors

Published in the Random EN group
Hello! Today we will talk about classes in Java. Classes can be said to be the core of Java programming. When you become a programmer, your main task will be to write your own classes with different functionality. Introduction to classes: writing your own classes, constructors - 1Let's figure out what this thing is and how it works :) As you already know, Java is an object-oriented programming language. All programs consist of objects that are somehow connected to each other. A class is essentially a template for an object. It determines how an object will look and what functions it will have. Every object is an object of some class . Let's look at the simplest example:
public class Cat {

    String name;
    int age;

}
Let's say we are writing a program, and in this program we need cats for something (for example, we have a veterinary clinic with the ability to make an online appointment). We created a class Catand specified two variables for it - a string nameand a number age. Such class variables are called fields . Essentially, this is a template for all the cats we will create in the future. Each cat (class object Cat) will have two variables - name and age.
public class Cat {

    String name;
    int age;

    public static void main(String[] args) {
        Cat barsik = new Cat();
        barsik.age = 3;
        barsik.name = "Barsik";

        System.out.println("We created a cat named" + barsik.name + ", his age - " + barsik.age);
    }

}
That's how it works! We created a cat, gave it a name and age, and output it all to the console. Nothing complicated :) Classes most often describe objects and phenomena of the surrounding world. A cat, a table, a person, lightning, a book page, a wheel - all this will be created in your program using separate classes. Now let's take a look at the variables we created in the class Cat. These are called fields, or instance variables . The name, in fact, reveals their entire essence. Each instance (object) of the class will have these variables Cat. Each cat we create will have its own variable nameand its own age. It’s logical, in general: with real cats everything is the same :) In addition to instance variables, there are others - class variables , or static ones. Let's add to our example:
public class Cat {

    String name;
    int age;

    static int count = 0;

    public static void main(String[] args) {
        Cat barsik = new Cat();
        barsik.age = 3;
        barsik.name = "Barsik";
        count++;

        Cat vasia = new Cat();
        vasia.age = 5;
        vasia.name = "Vasya";
        count++;

        System.out.println("We created a cat named" + barsik.name + ", his age - " + barsik.age);
        System.out.println("We created a cat named" + vasia.name + ", his age - " + vasia.age);

        System.out.println("Total number of cats = " + count);
    }
}
Console output:

Мы создали кота по имени Барсик, его возраст - 3
Мы создали кота по имени Вася, его возраст - 5
Общее количество котов = 2
Now we have a new variable in our class - count(quantity). She is responsible for counting the created cats. Each time we create a cat in the main method, we increment this variable by 1. This variable is designated by the static keyword . This means that it belongs to the class , and not to a specific object of the class. Which, of course, is logical: if each cat should have its own name, then we need one cat counter for all. This is exactly what the word static allows you to achieve - countthe same variable for all cats. Please note: when we print it to the console, we do not write barsik.countor vasia.count. She does not belong to either Barsik or Vasya - she belongs to the whole class Cat. Therefore, it’s simple count. You can also write Cat.count- that will also be correct. nameThis would not work with outputting a variable to the console :
public class Cat {

    String name;
    int age;

    static int count = 0;

    public static void main(String[] args) {
        Cat barsik = new Cat();
        barsik.age = 3;
        barsik.name = "Barsik";
        count++;

        System.out.println("We created a cat named" + name + ", his age - " + barsik.age);

        System.out.println("Total number of cats = " + count);
    }
}
Error! nameEach cat has his own. This is where the compiler gets confused. "Output the name to the console? Whose name is it? :/"

Methods

In addition to variables, each class has methods. We will talk about them in a separate lecture in more detail, but the general points are quite simple. Methods are the functionality of your class; what objects of this class can do. You are already familiar with one of the methods - this is the main(). But the method main, as you remember, is static - that is, it belongs to the entire class (the logic is the same as with variables). And ordinary, non-static methods can only be called on specific objects that we have created. For example, if we want to write a class for a cat, we need to understand what functions the cat should have in our program. Based on this, let's write a couple of methods for it:
public class Cat {

    String name;
    int age;

    public void sayMeow() {
        System.out.println("Meow!");
    }

    public void jump() {
        System.out.println("Jumping gallop!");
    }

    public static void main(String[] args) {
        Cat barsik = new Cat();
        barsik.age = 3;
        barsik.name = "Barsik";

        barsik.sayMeow();
        barsik.jump();

    }
}
Well, now our class is much more like the description of a real cat! Now we don’t just have a cat called Barsik with a name and age. He can also meow and jump! What kind of cat is there without such “functionality” :) We take a specific object - barsik, and call its methods sayMeow()and jump(). We look at the console:

Мяу!
Прыг-скок!
A real cat! :)

Creating your own classes. Abstraction

In the future you will have to write your own classes. What should you pay attention to when writing them? If we're talking about variables, you need to use something called abstraction . Abstraction is one of the four fundamental principles of object-oriented programming. It involves highlighting the main, most significant characteristics of an object , and vice versa - discarding secondary, insignificant ones. For example, we are creating a file of company employees. To create employee objects, we wrote a class Employee. What characteristics are important to describe an employee in a company file? Full name, date of birth, social security number, tax identification number. But it’s unlikely that we need his height, eye and hair color in a company employee’s card. The company does not need this information. Therefore, for the class Employeewe will set the variables String name, int age, int socialInsuranceNumberand int taxNumber, and we will abandon information that is unnecessary for us (such as eye color) and abstract it away . But if we create a file of photo models for a modeling agency, the situation changes dramatically. To describe a fashion model, height, eye color and hair color are very important to us, but the TIN number is absolutely not important to us. Therefore, in the class Modelwe need to create variables int height, String hair, String eyes. That's how abstraction works, it's simple! :)

Constructors

Let's go back to our cat example.
public class Cat {

    String name;
    int age;

    public static void main(String[] args) {
        Cat barsik = new Cat();

        System.out.println("Something has been happening in the program for 2 hours...");

        barsik.age = 3;
        barsik.name = "Barsik";

    }
}
Look at this code and try to guess what is wrong with our program. For two hours in our program there was a cat without a name or age! Of course, this is completely wrong. There should be no cats in the veterinary clinic's database without information about them. Now we leave it up to the programmer. If he doesn’t forget to indicate his name and age, everything will be ok. If he forgets, there will be an error in the database, unknown cats. How can we solve this problem? It is necessary to somehow prohibit the creation of cats without a name and age. This is where constructor functions come to our aid . Here's an example:
public class Cat {

    String name;
    int age;

    //constructor for class Cat
    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {

        Cat barsik = new Cat("Barsik", 5);
    }
}
A constructor is essentially a template for class objects. In this case, we specify that for each object cattwo arguments must be specified - a string and a number. If we now try to create a nameless cat, we will not succeed.
public class Cat {

    String name;
    int age;

    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {

        Cat barsik = new Cat(); //error!
    }
}
Now that a class has a constructor, the Java compiler knows what the objects should look like and does not allow objects to be created without the arguments specified in it. Now let's look at the keyword thisthat you see inside the constructor. Everything is simple with him too. "this" in English means "this, this". That is, this word indicates a specific object. Code in the constructor
public Cat(String name, int age) {
    this.name = name;
    this.age = age;
}
can be translated almost literally: " name for this cat (which we are creating) = the name argument that is specified in the constructor. age for this cat (which we are creating) = the age argument that is specified in the constructor." After the constructor fires, you can check that our cat has been assigned all the necessary values:
public class Cat {

    String name;
    int age;

    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {

        Cat barsik = new Cat("Barsik", 5);
        System.out.println(barsik.name);
        System.out.println(barsik.age);
    }
}
Console output:

Барсик
5
When the constructor has completed:
Cat barsik = new Cat("Barsik", 5);
The following actually happened inside:
this.name = "Barsik";
this.age = 5;
And the object barsik(it is this) was assigned values ​​from the constructor arguments. In fact, if you do not specify constructors in the class, it will still fire the constructor ! But how is this possible? O_O The fact is that in Java all classes have a so-called default constructor . It doesn't have any arguments, but it fires every time any object of any class is created.
public class Cat {

    public static void main(String[] args) {

        Cat barsik = new Cat(); //this is where the default constructor worked
    }
}
At first glance this is not noticeable. Well, we created an object and created it, where is the designer’s work? To see this, let’s write Catan empty constructor for the class with our own hands, and inside it we’ll output some phrase to the console. If it is displayed, then the constructor has worked.
public class Cat {

    public Cat() {
        System.out.println("Created a cat!");
    }

    public static void main(String[] args) {

        Cat barsik = new Cat(); //this is where the default constructor worked
    }
}
Console output:

Создали кота!
Here is the confirmation. The default constructor is always invisibly present in your classes. But you need to know one more feature of it. The default constructor disappears from the class when you create some constructor with arguments. The proof of this, in fact, we have already seen above. Here in this code:
public class Cat {

    String name;
    int age;

    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {

        Cat barsik = new Cat(); //error!
    }
}
We couldn't create a cat without a name and age because we defined a constructor for Cat: string + number. The default constructor disappeared from the class immediately after this. Therefore, be sure to remember: if you need several constructors in your class, including an empty one, you need to create it separately . For example, our veterinary clinic wants to do good deeds and help homeless cats, whose names and ages we do not know. Then our code should look like this:
public class Cat {

    String name;
    int age;

    //for domestic cats
    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //for street cats
    public Cat() {
    }

    public static void main(String[] args) {

        Cat barsik = new Cat("Barsik", 5);
        Cat streetCat = new Cat();
    }
}
Now that we've explicitly specified a default constructor, we can create both types of cats. In the constructor, you can assign values ​​explicitly, and not just take them from the arguments. For example, we can record all street cats in a database under the name "Street cat number...":
public class Cat {

    String name;
    int age;

    static int count = 0;

    public Cat() {
        count++;
        this.name = "Street cat number" + count;
    }

    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {

        Cat streetCat1 = new Cat();
        Cat streetCat2 = new Cat();
        System.out.println(streetCat1.name);
        System.out.println(streetCat2.name);
    }
}
We have a variable countthat is a street cat counter. Each time we run the default constructor, we increment it by 1 and assign that number as the cat's name. For a constructor, the order of the arguments is very important. Let's swap the name and age arguments in our constructor.
public class Cat {

    String name;
    int age;

    public Cat(int age, String name) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {

        Cat barsik = new Cat("Barsik", 10); //error!
    }
}
Error! The constructor clearly describes: when creating an object, Catit must be passed a number and a string, in that order . That's why our code doesn't work. Be sure to remember this and keep this in mind when creating your own classes:
public Cat(String name, int age) {
    this.name = name;
    this.age = age;
}

public Cat(int age, String name) {
    this.age = age;
    this.name = name;
}
These are two completely different designers! Now solve a few problems to consolidate the material :)
  • Museum of Antiquities.
Your task is to design the class Artifact. The artifacts kept in the museum are of three types. The first is about which nothing is known except the serial number assigned by the museum (for example: 212121). The second is about which the serial number and the culture by which it was created are known (for example: 212121, “Aztecs”). The third type is about which the serial number is known, the culture by which it was created, and the exact age of its creation (for example: 212121, “Aztecs”, 12). Create a class Artifactthat describes the antiquities stored in the museum, and write the required number of constructors for it. In the method main(), create one artifact of each type.
public class Artifact {

    public static void main(String[] args) {
    }
}
  • Meeting website
You are creating a user database for a dating site. But the problem is that you have forgotten in what order they need to be specified, and you don’t have the technical specifications at hand. Design a class Userthat will have fields - name ( String), age ( short) and height ( int). Create the required number of constructors for it so that the name, age and height can be specified in any order.
public class User {

    String name;
    short age;
    int height;

    public static void main(String[] args) {

    }
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION