We are going to cover classes and objects in Java. First, keep in mind that Java is an Object Oriented Programming(OOP) language.
1. Objects in Java
Objects in Java are representations of real-world objects. Think of objects around you. Some are table, books, chair, computer, mouse, dog, phone and lots more. Since there are not data types for all of these, we can use objects to represent them in Java.
An object must therefore have two things:
For example a phone has a model and color(attribute). A phone can make calls (behavior). An animal has type(attribute), color (attribute). Also, an animal can make sound (behavior), can move(behavior).
Now, an object can be create in Java using Classes
2. Classes in Java
You can create objects in Java by defining a class. A class provides a definition for the attributes and behavior of objects. Attributes are represented as method. Similarly, behavior is represented as methods. Let’s take an example.
Listing 1.0: Animal class in Java
A class can have the following three elements.
Local Variables : These a variables defined inside a method. For instance, numberOfLegs in the animal class.
Instance Variables: These are variables defined outside a method. We use them with an instance or object of the class.
Class Variables: These variables belong to a class. Class variables are defined within a class. Therefore, you define them using static keyword. For example, numberOfAnimals.
3. Constructors in Java
All Java classes have a constructor. If however, you don’t provide a constructor, then a default constructor is available. A constructor is a special function defined in a class. We use a constructor to create new objects. Each time you create a new object, you invoke a constructor. Take for example the code in Listing 1.1.
Listing 1.1: Vehicle class with a constructor
Note the following about constructors:
- the constructor has the same name with the class
- you don’t specify any return value for constructors
Furthermore, you can have more than one constructor in a class. However, the difference would be in the number of parameters.
Listing 1.2: Class with two constructors
You can play around with these codes. But we would take some examples later.
Finally we would see how to create new objects. This we would see in the next tutorial.