Programming Basics 6 – Classes and objects

Introduction

In this part we’ll discuss the most important concept in an object oriented language: Objects. So far you’ve already learned how to write a single class and you’ve put all your functionality into a single class. But we’ve used objects in our examples already and in this part you’ll learn what objects are and how you can use them!

Some theory

So far all of our program’s functionality was put into a single class with methods and fields:

public class ClassA
{
    private int field1 = 0;
    private Person obj = new Person();

    public void method1(String param1){ }
}

You can see a class, ClassA, with class variables and a method in it. If you look closely, you can already see an object here. Look at the obj-variable. It is an object of the Person-class. An object is an instance of a class and is created with the help of the ‘new’-keyword. This process is referred to as instantiating a class. In Java you can create an object of any class available, however some classes might not have any object specific fields or methods. After you’ve created an object, each object will hold it’s own copies of the fields and methods you’ve defined in the class. Let’s look at the code from the snippet above. If we create a graphical representation of this class, we’ll end up with something like this:

klassendiagramm
Figure 1: Class diagram with ClassA and Person

In the drawing you can see, that the Person class defines two fields and a method. You can of course use these fields and methods in other classes, because they are public:

public class ClassA
{
    private int field1 = 0;
    private Person obj = new Person();

    public void method1(String param1)
    {
        System.out.println(person.name + "s age: " + person.age);
        obj.haveBirthday();
        System.out.println(person.name + "s age: " + person.age);
    }
}

As you can see, you can use an object’s public fields and methods by writing a method’s name before the field- or method name. If a field is private, it can not be used from the outside of a class. Refer to part 2 of the series for access modifiers.

Declaring classes

It shouldn’t be a huge surprise but you can define a new class with the following syntax:

access_mod class class_name
{ }

Everything inside the two curly brackets will be grouped together to a class. In Java each file has to have a public class with the same name as the file. For example if you create a new java-file with the name BestAlgorithm you have to have exactly one public class with the name BestAlgorithm in it. Ideally class names start with a capital letter, but it’s not mandatory.

You can have multiple classes inside a file, as long as the other ones are marked as private:

public class Class1
{ }

private class Class2
{ }

Multiple objects

In the beginning of this part I said, that different objects (of the same class) will have their own copies of the contained fields and methods. So if you change an object’s field it won’t automatically change another object’s respective field’s value. For example:

public class Employees
{
    Person cashier = new Person("Bill", 25);
    Person manager = new Person("Sarah", 34);

    System.out.println(cashier.getData());
    System.out.println(manager.getData());

    // Today is Sarah's birthday
    manager.haveBirthday();

    System.out.println(cashier.getData());
    System.out.println(manager.getData());
}

The output will look like this:

Bill is 25 years old
Sarah is 34 years old
Bill is 25 years old
Sarah is 35 years old

As you can see, only Sarah’s age got updated, because we called her haveBirthday-method. Remember that, as long as an object’s field or method is not marked as static, it will only belong to this single object. It won’t affect other objects, even if they are instances of the same class.

But did you notice something unusual in this snippet? Let’s look at the line where I created the new Person-objects:

Person manager = new Person("Sarah", 34);

You might have not seen this type of instantiation yet but it is really useful. You can create a new object and pass it some values it should have at the time it is created. This is done by a special method of the Person-class. Take a look at figure 1 from above. Can you see which method is the so called constructor?

Constructors

As you can see in figure 1, an object’s constructor is not like a regular method, it is a special case. It always has the exact same name as the class (it’s case sensitive!) and it has no return type, not even void, as it returns a new instance of the class it is in, internally. The following snippet shows an example:

public class Car
{
    // Default constructor
    public Car()
    { }

    public Car(String make, String model)
    { }

    public Car(String make, String model, int hp, int torque)
    { }
}

As you can see, it’s possible to overload (have a different set of parameters) the constructor, just like any other method. If you want to refresh your method skills, take a look at part 3 of this series!

If you don’t define any constructor at all, you class will automatically gets a default constructor which doesn’t set any values of your class and simply returns a new instance of the class.

The static keyword

Earlier in this article I showed you, that objects will hold their own copies of variables and methods and therefore if you change one object it won’t affect the others.

But what if you want certain values to change for all objects if you change them? You can mark these values as ‘static’. For example:

public Class Circle
{
    public static float PI = 3.14f;
}

Now you definitively don’t want to define PI for each circle, because it will always be around 3.14. Therefore it is unnecessary to keep a copy of PI for each object. If you now alter this value for an object, it will automatically change in the class, the object is created from and therefore it’ll also change for all the objects. The same applies to methods. And the good thing about static variables and methods is, that you don’t need to create an object to use them, because they belong to the class itself rather than an object. That’s why you can call some methods and use some values without having to create an object:

// Works without having to create an object
// of the output stream
System.out.println();

This

Sometimes you need to explicitly tell the program what value to use. We discussed earlier in this series, that values are always valid in a specific context. For example in a method or in a class. Let’s think of a problem, similar to the one discussed at the very end of part 3:

public class VariableTest
{
    private int x = 1000;

    public VariableTest(int x)
    {
        // Assign x's value to x
    }
}

You can see that in the class we have a variable called x. We also have a variable called x in the constructor. Now we want to assign x to x. But how can we do that? How does the compiler know what x we want to assign? Of course you could change the method to something like this:

public VariableTest(int otherVariableName)
{
    x = otherVariableName;
}

That’s a possibility, but it might not satisfy you. You have to tell the compiler which x you mean. You can do that by telling it, that you want to use the object’s x (which is declared outside the method). If you don’t tell it to use the class variable, it will assign the method’s x to itself, wich doesn’t make any sense at all. You can tell the compiler that you want a class variable (or method) to be used with the help of the ‘this’-keyword:

public class VariableTest
{
    private int x = 1000;

    public VariableTest(int x)
    {
        this.x = x;
    }
}

That will assign the value of the method’s x to this classes x.

Comparing objects

In part 5 of this series we discussed how to compare primitive datatypes. You can compare objects with the relational operands (== for equality and != for inequality), but this might not give you the results you’d like to have. Let’s look at the following example:

public class ObjectComparer
{
    Person a = new Person("Jim", 48);
    Person b = new Person("Jim", 48);
}

You can see two different objects with the same values. We want to check, if the two persons have the same name and age. But if you compare them with the operands, mentioned above, will they be equals?

if(this.a == this.b)
    System.out.println("This is the same person!");

The output will be blank, because this is not the same object. The == operand compares two objects by their reference (the address they have in the java virtual machine’s RAM), rather than by their values. If you want to compare two objects by their values, you have to use the equals method. Each class automatically has this method, but you have to override it, to use it properly. Don’t worry if this confuses you, we’ll talk about overriding a method in a more advanced series. For now you can just think of it as creating a new equals method:

public class Person
{
    // ... other contents of the person class

   public boolean equals(Object other)
   {
        // Check if the other object is
        // an object of type Person
        if(other instanceof Person)
        {
            if(this.name == other.name && this.age == other.age)
                return true;
        }

        return false;
   }
}

This way the object’s values will be compared instead of their references and the following code will show the desired behaviour!

if(this.a.equals(this.b))
    System.out.println("This is the same person!");

However if you want to compare two objects to see if they are the same one, using the == or != operands is fine!

Instanceof

You’ve seen me using the instanceof keyword above. This keyword is used to check wether an object is an instance of a Class. It is just used as you can see it above and I just wanted to mention it here, so this article is complete!

Conclusion & Exercise

That was another long article and I hope you enjoyed it! Basically you have to remember that an object is an instance of a class and it is created with the new keyword. In Java you can create an object of any class, because every class written in Java, is also an Object (we will discuss this in another series with more advanced topics).

Now let’s make an exercise to remember this topic! Create an application that manages employees. Use the Person-class shown above and your knowledge, you obtained in this series, to create an application that does the following:

How would you solve this exercise? Leave me your ideas in the comments! We’ll discuss the solution in the final part of this series. Have fun!

Table of contents

Part 1 – MyFirstProgram
Part 2 – Access Modifiers and Variables
Part 3 – Methods
Part 4 – Arrays
Part 5 – Control flow
Part 6 – Classes and Objects (You are here)
Part 7 – Exceptions and exception handling

comment-banner

Advertisements

8 thoughts on “Programming Basics 6 – Classes and objects

Leave your two cents, comment here!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s