1. Adding properties
Welcome back! Now let's discuss what properties in Java are.
2. Car example
For this example, let's take a look at a car. When we see cars driving, we can distinguish individual cars from one another because each car has specific properties that we use to differentiate them.
3. Differentiate cars
When we encounter cars of the same color and model, we can examine their license plate number to determine whether they are separate cars.
In the same way you think of a car's color and plate number, you can think of class properties. Class properties are pieces of information that describe a class in detail and allow us to differentiate between each object instance created.
4. Adding properties to class
To add a property to a class, we find a line within the curly brace of a class definition, specify the data type for the property, and then provide the property name for the class property before ending the statement. Here, we add the property model to the Car class. We can add multiple Properties within a class, and the properties can be of different data types. For example, using our car analogy, the make of the car could be a string property, the top speed could be an integer, and there could be a boolean property that holds information whether the car is insured or not.
5. Constructors in Java
So far, we have seen how to add properties, but not how to set their values. In Java, we assign values using the constructor. The constructor is a method always called when an object is being created. To create a constructor, we create a method with the same name as our class. If we use a `Passport` class, the constructor will be a method called `Passport()`.
6. Setting properties inside the constructors
To set values for class properties, we use the `this` keyword to access the property we want to set by adding a dot after it, followed by the property name. The `this` keyword in Java refers to the current object, not the class itself, and allows access to the object's properties and methods.
7. Constructors with parameters
Constructors can take parameters like any method, making our objects more dynamic. In our example, we can add a parameter `firstName` and `lastName` to our `Passport` constructor.
8. Setting properties with constructor parameters
We then set the values of our class properties to be the values of the parameters.
9. Creating object instances with parameters
Suppose we create a `Passport` object,` myPassport`; we can pass the `firstName` and `lastName` to the constructor by inserting sample values `"Michael"` and `"Jackson"` as strings within the brackets of the `Passport()` class name after the new keyword. Printing the `firstName` property of the `myPassport` object will display `"Michael"`.
10. Let's practice!
Properties and constructors are core OOP concepts, and it's your turn to start adding them to classes.