Software Development Basics – Classes and Objects

Now that you know how to separate your code in methods, the next step is to learn about classes. Classes will not only let you organize your code in a better way, but it will also let you start diving into what is known as Object Oriented Programming, one of the most popular and powerful ways of coding today.

 

Classes

 

A class is a programming construct that enables you to define your own custom types. In a class you define a behavior (methods) and characteristics (member variables) that are shared across all instances of a class. You will use your class as a template to create objects. When you do this it is said that your new object is an instance of that class, or if you want to see it this way, your new object is a “copy” of your class.

 

When you create a class, you can create “copies” of that class, each one having an independent “life”. Imagine that you have a class Person, that has methods for all the actions we can perform and variables that can hold all our characteristics. You can see this as a template class for creating persons. And each one of us will be a different “object” of type Person. An object can be anything you like, it is just a concept to visualize a data structure with the behavior and characteristics that will be useful to you. And also it is a way to reuse code.

 

When you create a new object based on the Person class, it is said that you create an instance of that class. All the objects that are instances, or based-on, the same class share the same methods and properties (behavior and characteristics), but can have different values to them.

 

You will normally have many classes in a single project.

 

Classes are basic for the next block in our Software Development Basics series: Object Oriented Programming.

 

Class declaration

 

First you create a class in your project, you already know how to do this. You need to set the same name of your file than the one you give to your class. You need to declare your classes to start with. The most basic class declaration is as follows

class ClassName {

}

 

This is a class. You need to add behavior and state to it. For doing this, you add methods and variables to the class.

 

Important things to note in the class declaration:

  • Convention is to start your class name with uppercase letter.
  • You will see in the next posts that you can have a longer class declaration. The one that you see here is the most basic one.

 

In this post we will create the class called Person. You already know how to create a class, so just call it Person.

 

public class Person {

}

 

Adding Characteristics to your class

 

A Person – our class – can have first name, last name, age, a birthday, gender, etc. These are all characteristics of a Person.

 

You use member variables to add characteristics to your classes. You already know how to declare a variable. The difference here is that a member variable is declared at the top of the class and they can be used in any method in your class. They are also known as fields. Usually they have the private modifier so only the class can modify them.

 

Lets create some member variables for our Person class.

 

// Member variables. The scope of these variables is the entire class.
// Any method in the class can have access to them.
// Since they are private, they can only be accessed within this class.
// To use Date type, add this line before the class declaration: import java.util.Date;

private String firstName;
private String lastName;
private int age;
private Date birthday;
private String gender;

 

Since these variables are private, they are only accessible within your class. But the purpose of having this characteristics is that other classes can see their values and even modify them. So you need methods – called getters and setters – to get and set the values of your variables. These methods should be public, so other classes can access your class’s characteristics.

 

// Getter and setter methods. Methods used to read or modify
// the member variables of this class.
public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public Date getBirthday() {
    return birthday;
}

public void setBirthday(Date birthday) {
    this.birthday = birthday;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

You can create these methods automatically in Eclipse if you right-click -> Source -> Generate Getters and Setters

Adding Behavior to your class

A Person – our class – can have behavior; it can do several actions like breathe, wake up, talk, sleep. You can add this behaviour to your Person class using methods. For now, all our Person will do will be to print the action that is being done.


// Behavior for the Person object. All the objects
// created from this class will have access to these methods.
// you can add here whatever your class needs to do.

public void wakeUp(){
    System.out.println(firstName + " is waking up...");
}

public void goToWork(){
    System.out.println(firstName + " is going to work...");
}

public void sayMyName(){
     System.out.println("My name is " + firstName + " " + lastName);
}

 

As you already know, the public methods will be available outside your class. You can have private methods that can only be available within your class.

 

Class Constructor

 

A Constructor is a special method that is called when you create a new object from your class. You don’t need to provide a constructor since one is already there for you, although you cannot see it.

 

A Constructor can be used to initialize some variables from your class. If you need to do this, or another kind of operation when your object is being created, you can add one or more Constructors.

 

A Constructor has this general declaration form:

 

public ClassName(parameter list){

// operations to be done at object creation.

}

// Default constructor, no need to add it if you are not going to do anything
// at object initialization.

public Person(){

}

 

In our Person class, we need to provide some information at object initialization, so we are going to add a new constructor that receives as parameters all the Person information (first name, last name, age, birthday and gender).

 

// Constructor that receives different values to initialize the variables in this object.
// Note the this keyword. It is referring to the current instance of the class.
// So what these lines do is assign the received value to the current object instance
// variable.

public Person(String firstName, String lastName, int age, Date birthday, String gender){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.birthday = birthday;
    this.gender = gender;
    System.out.println("Person object initialized.");
}

 

Creating Objects

 

First, let’s provide some default information to the default constructor.

 

// Default constructor, no need to add it if you are not going to do anything
// at object initialization.

public Person(){
    firstName = "John";
    lastName = "Doe";
    age = 0;
    birthday = new Date();
    gender = "Male";
}

 

Now we need to create another class, selecting the option to add the Main method to it. Here we are going to create our new Person objects and use them.

 

In a general form when you create an object you need to do this:

ObjectType objectName = new ObjectType(constructor parameters);

 

We are going to create a Person object:

Person personOne = new Person();

 

We use the default constructor here.

 

Let’s create another Person object.

 

Person personTwo = new Person("George", "Harrison", 52, new Date(1943, 2,25), "Male");

 

Here we are using the constructor that receives all personal data.

 

Each time that you create an object, using the new keyword you are instantiating a class. An instance of a class is a new object of that class.

 

You can see here that you have two different objects, each one is independent from the other and unique, but share the same characteristic names and behavior (methods) but they will have different results.. After all both share the same Class as template.

 

Lets see this in action.

 

Using the Object Methods

 

We are going to use all the methods for personOne and personTwo:

 

// Use Person methods. You will have unique values for personOne.
// Since we used the empty constructor, you will see here the default
// values.

personOne.wakeUp();
personOne.goToWork();
personOne.sayMyName();

// Use Person methods. You will have unique values for personOne.
// Since we used the empty constructor, you will see here the default
// values.

personTwo.wakeUp();
personTwo.goToWork();
personTwo.sayMyName();

 

You will see this output:

 

Person One methods:

John is waking up…

John is going to work…

My name is John Doe

 

Person Two methods:

George is waking up…

George is going to work…

My name is George Harrison

 

Using Getter and Setter Methods

 

You can change and obtain the object properties using the setters methods:

 

// Using setter methods. We are going to change personOne's values
// using the setter methods that are available in the Person class.

personOne.setAge(72);
personOne.setBirthday(new Date(1942, 05, 18));
personOne.setFirstName("Paul");
personOne.setLastName("McCartney");

 

You can use the object properties using the getter methods:

 

// Using getter methods. Show the new values for personOne
System.out.println(personOne.getFirstName() + " " + personOne.getLastName());
System.out.println("age: " + personOne.getAge());
System.out.println("Birthday: " + personOne.getBirthday().toString());

 

You get this output

Paul McCartney
age: 72
Birthday: Sat Jun 18 00:00:00 CDT 3842

 

You can see that you have changed personOne’s values.

 

this keyword

 

We saw before a way to use the this keyword: in the constructor you use the this keyword to reference the current instance of the class. With this you differentiate from the constructor variable names and the class variable names.

 

Also you can use the this keyword to call another constructor from the same class.

 

We are going to add another constructor to our Person class.

 

public Person(String message){
    System.out.println(message);
}

 

We are going to call this constructor form the parameterless constructor. We are going to use this new one to print a message.

 

// Default constructor, no need to add it if you are not going to do anything
// at object initialization.
// this("calling another constructor") will call the constructor that receives
// a string value.

public Person(){
    this("Calling another constructor");
    firstName = "John";
    lastName = "Doe";
    age = 0;
    birthday = new Date();
    gender = "Male";
}

 

This will cause the message to print in the Console when you create a new object.

 

—–

 

There is a lot more about classes, but with this we can move forward to an important topic: Object Oriented Programming. After covering the basics of OOP we are going to get back to more advanced features of classes.

 

You can find the code for this post in GitHub.

 

 

Questions? Leave a comment or email me.

 

Leave a Reply

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s