Java, Java Tutorial, Software Development

Chapter 6: Java Object And Its Properties And Behaviors

We write codes that create Java objects from Java classes. These can have properties and behaviors. Properties are data with names; while, behaviors are the actions an object can perform on its properties. Consider the following Java class without properties and behaviors.

A Java class without properties and behaviors is generally useless. If that Java class is to have properties and behaviors, we will rewrite it as follows.

The class now has four properties and eight behaviors.

Java Object Properties Are Named Data

Java objects can have properties and behaviors. Properties are data with names because we can refer to them using variables. For instance, we refer to data “Toyota,” “Fortuner,” “2018”, and “Philippines” using make, model, year, and country, respectively.

Technically, these names are variables in the computer programming context. Specifically, we have instance variables. We’ll dive into more technical stuff in later posts.

Behaviors Are Actions On Data

Behaviors are actions a Java object can perform on its data. To design behaviors in a class, we write methods. Consider the following methods from our modified class.

How To Use The New Class

Consider the following startup class that uses our class that now has properties and behaviors.

When we run these codes, we get the following output.

The codes create a “default” car on line 8. We call it default because it already has data for its make, model, year, and country. We use four methods to retrieve the car’s data by calling them on the Java object itself.

For example, to get the car’s make, we’d use the following code.

We can change the data of the Java object using its behaviors.

The codes generate the following output.

Although we started with a Toyota Fortuner, we changed the car’s properties using its behaviors. Then, when we retrieved the make again and got a different value. Now, the car is a Mazda6.

What’s Next?

There is more to Java classes than meet the eyes. Next, we’ll go through the access modifiers for classes.

Chapter 7: Java Classes And Access Modifiers – Review

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like