JAVA · ОСНОВЫ · LESSON 20

Name upon creation

Designer · about 17 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

Designer meets object

A constructor is called when an object is created. His name matches the class name. He can immediately get the name of the pet.

class Cat {
    String name;
    Cat(String newName) {
        name = newName;
    }
}

✦ Now the cat can be named immediately.

STEP 2

Pass the name to new.

When creating, specify the word in parentheses. The designer will save it in the object field.

Cat cat = new Cat("Рыжик");
System.out.println(cat.name);

✦ It'll make Red.

IN-CLASS PRACTICE

Type the code yourself

Type an example manually. Check the signs and brackets.

public class Main {
    public static void main(String[] args) {
        Cat cat = new Cat("Рыжик");
        System.out.println(cat.name);
    }
}
class Cat {
    String name;
    Cat(String newName) {
        name = newName;
    }
}
Open the editor for class work
HOMEWORK

Solve it yourself

Make a Dog class with a String name field and a Dog constructor (ZString newName), which retains the name. In main, create Dog with the name «Бим» and output dog.name.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework