Lesson 4: Classes and Objects

Introduction:

In lesson 4, we will talk about one of the most important features of object-oriented programming and Java: Classes and Objects!

What is a class? In life, you can find many things which are of the same type - classified by its similar behaviors. For example, BMW, Benz and many others cars all have the same framework (wheels, car body, etc) and are hence part of the same class: Car. In object-oriented language, we can define the brand of cars as instance objects of the class: Car. In other words, a class is a blueprint from which individual objects are created. To clarify things and provide further insight into Classes and Objects, I quote Steve Jobs (from a 1994 Rolling Stone interview):
"Objects are like people. They're living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember things. And rather than interacting with them at a very low level, you interact with them at a very high level of abstraction, like we're doing right now. Here's an example: If I’m your laundry object, you can give me your dirty clothes and send me a message that says, “Can you get my clothes laundered, please.” I happen to know where the best laundry place in San Francisco is. And I speak English, and I have dollars in my pockets. So I go out and hail a taxicab and tell the driver to take me to this place in San Francisco. I go get your clothes laundered, I jump back in the cab, I get back here. I give you your clean clothes and say, “Here are your clean clothes.” You have no idea how I did that. You have no knowledge of the laundry place. Maybe you speak French, and you can’t even hail a taxi. You can’t pay for one, you don’t have dollars in your pocket. Yet I knew how to do all of that. And you didn’t have to know any of it. All that complexity was hidden inside of me, and we were able to interact at a very high level of abstraction. That’s what objects are. They encapsulate complexity, and the interfaces to that complexity are high level."

Now that you have a clearer understanding of what Classes and Objects are, let's get started with Java.

4.1 Creating classes:

Now you may wonder: How do you create a class in Java? Have a look at the example below:

public class Car{

    //All cars have these features, so we put instance variables here.
    private int speed;
    private string brand;
    private int wheel_numbers;

    //This is a constructor. When an object is instantiated, it must initialise these three vairables. 
    //It will be explained further in 4.2.

    public Car(int startSpeed, string brand, int wheels){
        this.speed = startSpeed;
        this.brand = brand;
        this.wheel_numbers = wheels;
    }  

    //a method used to change the value of an instance variable out of this class.
    public setSpeed(int newSpeed){
        speed = newSpeed;
    }

    //a method used to get the value of an instance variable out of this class.
    public getSpeed(){
        return speed;
    }

    public increaseSpeed(int increment){
        speed += increment;
    }

}

As shown in the example above, a class should include variables and methods and I will explain it more particularly. Variable is a basic part of a class and it includes static variables and instance variables. These variables can be equal to the features of an object. For instance, if a class called people and it includes following variables: eyes color, hair color and skin color, then each object of this class will have different eyes color, hair color and skin color.

private int speed; // this is a general variable

Instance variables should always be written at the top of a class and it should include the modifier, data type (int, char, string, etc) and the name of the variable.

For methods, these are functions in a class and these can be explained to the motions of a class. In above code, increaseSpeed is a general method and when an object of this class is instantiated in the main function, this object can use this method to change its instance variable speed. In addition, you can find that there has a method that has the same name with the class, called Car. Actually, constructor is a special method and it will be called when an object is created, to assign instance variables of this object.

modifier dataType methodName(dataType parameter){
    method body
}

If you have learned C language, you will find that the Java method is quite similar to the function in C. Since Java is a objective-oriented language, its methods have objective features. Therefore, a method can be called by different objects if the method is public. So, how can we use our class in the main function?

4.2 Instantiating classes

An object is an instance of a class, and the process to create this object is called instantiation. Instantiating classes will occur when you want to use methods of class out of this class. For example, we have a transportation class and it includes a method – run, which can make a kind of transportation run. If you want to use this method, you can’t just say “Hey! Transportation run!” It will be vague since computer doesn’t know which transportation you want to run. Therefore, we need a specific object to implement this method. You need to create an object – car, and use this object to call the run method. Then the car will run.

In Java, we always use a keyword – new, to create an object and there are three steps: declaration, instantiation and initialization.

  • Declaration: Declare an object; include object name and the type of this object.
  • Instantiation: Use the keyword new to create an object.
  • Initialization: when we use new to create an object, constructor will be called to initial the object.

Person allen = new Person();

The code above is a simple instantiation of an object allen. Person is the type of the object, allen is the object name and new Person() is the initialization. The empty parenthesis: () means that there are no constructors in the class and the instance variables in the class will all be set to its default value.

Take another example:
Car newCar = new Car(80, Benz, 4);

Car is the class I wrote above, and this code means I create a new object call newCar and it has been initialized with speed 80, 4 wheels and its brand is Benz. Why can this object initial with these parameters? That is because of constructor.

public Car(int startSpeed, string brand, int wheels){
    this.speed = startSpeed;
    this.brand = brand;
    this.wheel_numbers = wheels;
}

This is a constructor and it must have the same name with the class. When we use new Car(80, Benz, 4), these parameters will send to the constructor and the startSpeed will be assigned 80, the brand will be assigned Benz and the wheels will be assigned 4. Then these instance variables in the class: speed, brand and wheel_numbers will be assigned. It is important to remember that if a class has a constructor, we must initial instance variables when an object of this class be created. If a class doesn’t have a constructor we can just create an object and leave the parameter brackets blank: Person allen = new Person();

After we created an object, we can access the method of the object:

Car newCar = new Car(80, Benz, 4);
newCar.increaseSpeed(20);
newCar.getSpeed();
newCar.setSpeed();

It is quite simple since we just use dot to access these method and we can use getSpeed and setSpeed to operate instance variables inside the class. Why can’t we just use newCar.speed to get the value of this instance variable? Because this variable is private and we can only get the value of this private variable through the getSpeed method.

4.3 Static and Instance methods/variables

Static and instance is an important part of Java, I will explain it by two parts: static and instance variables and static and instance methods.

Static variables has a keyword static in the declaration of this variables:
public static dataType variableName;
When a static variable is declared, the program will allocate memory for this variable and if this static variable changes in one object or in the class directly, this static variable of all objects will be changed at the same time.
For instance: if we have an object personA and object personB and we also have a static variable hairColor,

People personA = new Person();
People personB = new Person();
personA.hairColor = “RED”;
System.out.println(personB.hairColor);

From the code above, you will find that console will print “RED” on the screen. Moreover, static variable can be used by class name directly in another class without instantiating a new object.
People.hairColor = “RED”
Comparing with static variable, instance variable won’t be allocated storage before an object be created and it must be called after creating a object. In addition, when this variable changed in an object, it won’t affect others objects.

Static method’s features are similar to static variable and it also has a keyword static before the datatype: modifier static dataType methodName(dataType parameter) Static method can be called without instantiation from another class. But instance method must be called with a object be created. Now I have a question: Why can instance method calls instance variables and static variable, yet static method can’t calls instance variable? That’s because static method can be used before an object be created, and at that time instance variable haven’t be allocated storage. One last question: Why is the main method static?

4.4 Using encapsulation

One of the core features of Java is encapsulation. So what is encapusulation? Generally, encapusulation means we need hide all of the member variables and implementation details and do not allow the outside of this class to call directly. And we should give the outside methods to let them call and operate member variables safely.

What is the function of encapsulation? Firstly, users can only access data through default methods and it can protect member variables from some unreasonable call. Secondly, it will be easier for modification and improving the maintainability of codes.

There are four common modifiers: private, default, protected and public. Private only allow the call inside the class and default means we don’t add any keyword before the method or variables, and we can use default methods/variables free in a package. Protected means this method/variable only availiable for the subclass of the class this method/variable in. Public means you can use this method/variable anywhere! Modifier can be used in class, method, variable and also the constructor. Furthermore, most member variables should be modified by private unless some member variables modified by static.

Exercise:

In our final project, we will create a real whack-a-mole game. Therefore, Let's try to make a simplest console whack-a-mole game with our knowledge first! It will involves all we learnt in Chapter 4. There is the requirements:

a) The game should have 9 holes and arranged into 3*3 matrix.

b) Allow users to hit the moles in console.

c) Every time users hit a mole, a new mole will come out from a random hole.

d) Every time users hit a mole, users will get scores and at the end of this game, the total score will be shown.

e) The game need a timer to limit the length of this game.

f) When users hit wrong hole, game over. When the time out, game over.

Hints:

   1. You may need multiple classes in this exercise.
   2. You can use Scanner class to get users' input.
   3. You may need ArrayList to manage your holes.
   4. You can use System.currentTimeMillis() to get the total run time of this program.
   5. Remember to use while and for loops in your program.
   6. Tou can use Random class to get a random number between a range of numbers.

(You can find the example in next page)