JAVA · ОСНОВЫ · LESSON 21

The subject can act.

Method of object · about 14 minutes

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

Action within the class

The object may have its own actions. The speak method within Cat uses the name of this particular cat.

class Cat {
    String name;
    void speak() {
        System.out.println(name + " мяу");
    }
}

✦ Every cat will say its name.

STEP 2

Call through the dot.

After creating the object, call his method through the point. So you ask a particular cat to talk.

Cat cat = new Cat();
cat.name = "Рыжик";
cat.speak();

✦ This is «Рыжик мяу».

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();
        cat.name = "Рыжик";
        cat.speak();
    }
}
class Cat {
    String name;
    void speak() {
        System.out.println(name + " мяу");
    }
}
Open the editor for class work
HOMEWORK

Solve it yourself

In the Dog class, make the name field and the speak() method, which outputs name and « гав». Create a dog called «Бим» and call speak.

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

Opening up your homework