"OK. Last time we dealt with classes. Today, I'd like to tell you how to create objects. It's very easy. You write the keyword new and then the name of the class that you want to create an object of."

Example
Cat cat = new Cat();
Reader reader = new BufferedReader(new InputStreamReader(System.in));
InputStream is = new FileInputStream(path);

"I already know this."

"I know you do. Keep listening."

"When creating an object, you can pass various arguments inside parentheses. More about that later today. For now, let's take a look at the Cat class:"

Java code Description
class Cat {
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
name is an instance variable. It has a public access modifier, making it visible anywhere in the project.

The getName method is a getter. It returns the value of the instance variable name. The method's name was derived from the word 'get' plus the variable's name with an uppercase first letter.

The setName method is a setter. It is used to assign a new value to instance variable name. The method's name was derived from the word 'set' plus the variable's name with an uppercase first letter. In this method, the parameter has the same name as the instance variable, so we precede the name of the instance variable with this.

"What are these getters and setters?"

"In Java, it's common practice to hide variables from other classes. Usually, variables declared inside classes have the private modifier."

"To allow other classes to change the value of these variables, a pair of methods is created for each of them: get and set. The get method returns the current value of the variable. The set method sets a new value for the variable."

"And what's the point?"

"If we don't want anyone to change the value of an instance variable, we can just not create a set method for it or we can make it private. We can also add additional data checks to the method. If the passed new value is invalid, nothing will be changed."

"I see."

"Because a class can have a lot of variables, the names of get and set methods usually include the names of the variable they deal with."

"If a variable is called 'name', then the methods will be called setName and getName, etc."

"I see. That seems quite reasonable."

"Here are more examples of working with a newly created object:"

Step Code Description
1
new Cat();
Create a Cat object
2
Cat catOscar = new Cat();
Store a Cat object in the variable catOscar
3
catOscar.name = "Oscar";
catOscar.age = 6;
catOscar.weight = 4;
Fill the object with data: name, age, weight
4
catOscar.sleep();
Call a method on the object
5
catOscar.fight(catSmudge);
Make the objects interact.

A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.