Skip to Main Content

Data Structures

Computer Science Department

Object-Oriented Programming Review

What is Object Oriented Programming?

Object Oriented Programming is a style of programming which stores Data in Objects of different types. Each object type is defined by a Class with a corresponding .java code file (which are in project folders, the Java Dev. Kit (JDK), or imported libraries).

Each object is an instance of a class. It has it’s own specific data held in its class attributes.

What is Java?

Java is a High Level, Class Based, Object Oriented Programming language first released in 1996.  Click here for a Java syntax and functionality review.

Java has many useful features which can help us learn programming strategies. It is also a good jumping-off point to learn other programming languages while keeping the same fundamentals.

High Level – means that Java itself handles much of the System level work needed to make the language function. One of the key features is managing memory for variables/objects, using the Java Garbage Collector. The written code in Higher Level languages is often closer to human language (how we would describe a programs steps).

  • The lowest level programming language is Machine Language, consisting of pure Binary (Zeros and Ones). All code is converted to ML before the computer runs it.

Class Based – means that Code is organized into distinct Classes, which each contain information and executable methods for a specific type of object.

Java Classes

Classes define the attributes and methods an object has. A Class is like a blueprint for an object. In Java, each class is written in a .java file, which is then compiled into a .class file. Then the Java Runtime Environment (JRE) can import or run the .class files.

Let’s take a look at an example “Person.java” class, which as the name suggests, can be used to represent a person. This example java project can be downloaded here.

Inside the Example java project folder is a src folder, which contains a folder named “oop”. This inner folder is the java package which Person.java is inside.

In the Person.java file (and all other java files), the package statement is written at the top of the file. The package folder is inside the src folder, and contains the java file. In this case, the package is named ‘oop’.

The class declaration for the Person class comes directly after the package statement.

Normally, import statements go between the package name and class declaration, however Person.java does not have any. An example of some import statements are:

These can import java entire libraries, or specific packages/classes from those libraries. This allows us to use prewritten Java classes like ArrayLists, Stack, LinkedList, HashMap, StdIn, StdOut, Math, Random, and much more.

Within the body of a class, you can write Class Attributes, Methods which includes Constructors

Attributes – Variables which belong to a class object or the class itself. Can be defined as public or private, and with modifiers like final and static. Also called Fields.

The Person class has four fields.

  • String name – the Persons name
  • int age – the Persons name in days
  • double height – the Persons height in inches
  • static String species – the species of the person (Human)
    • This attribute is static, which means it’s the same for all Person objects

All four class attributes shown above are set to private, and thus need getter and setter methods. These which return and set a specific attribute.

Constructors – A method declared public/private with name “ClassName()” with no return type. This is the code that is called to setup (instantiate) a new object when it is made.

  • Constructors can have parameters, which can take in data about that instance of the object. i.e. Name, ID, Age, etc.
  • Multiple constructors can be declared, each with a different set of parameters, including one with no parameters. If no constructor is written, Java will instantiate the object with a default constructor.

The Person class has two constructors, with a different number of parameters.

  • The first constructor has three parameters, one for name, one for age in days, and one for height in inches
  • The second constructor has only one parameter, for the Persons name

Constructors are called with the “new” keyword, and should be assigned into a variable of that class type.

    Person john = new Person("John"); // Create a new person object with the name "John"
    Person amy = new Person("Amy", 9754, 63.2); // Create a new person object with the name "Amy"

  System.out.println(amy.getName() + ” and ” + john.getName()); // Prints “Amy and John”

Methods – Snippets of code which can be run, relating to a specific object (instance) or the general class itself (static).

The Person class has a getter and a setter for each of its four attributes. You can see that to access the attributes, you can either use their variable name directly or use the “this.” to specify that it is a class attribute.

  • The setter for the “species” attribute is static, which means it sets the species attribute for ALL Person objects, because it’s a static-class value

The Person class has three other methods:

  • returnAgeInYears() – returns the int year age
  • print() – prints name, age, and height of the person
  • compareTo(Person p) – compares this person to the given Person p. Returns true if they are the same.
 

Static methods/fields

Methods and Fields (not constructors) can also have the static modifier. Static means that they can be called/accessed without needing an object instance to call it on. Instead, we run and access these based on the class they are apart of.

  • Methods/variables without the static keyword are known as Instance methods/variables. They can only be run/accessed via an instance of the class.
  • For Example, to find the length of a string, you call the non-static length() method.  To do this, you need a actual String variable to call it on. You cannot do String.length(), as String is the class name, not an instance of the class.
    • Likewise, Integer.parseInt() is a static method. You call it based on the Integer class name itself, not on a specific instance of an Integer object.
  • Static Methods allow classes to contain utility methods adjacent to their object type which may be useful.

StdIn and StdOut are classes that heavily utilize static methods and variables. You don’t instantiate either class before you use them, you simply call the static methods StdIn.setFile(inputFile) or StdOut.setFile(outputFile). This sets the singular static filestream for either to the given input/output, and which can be accessed statically with the StdIn.readX() methods or StdOut.print() methods.

Generally, until you understand why you need static methods/attributes, avoid using them.

Full Person.java Class

In Summary, the Person class has:

  1. 3 non-static class attributes
  2. 1 static class attribute.
  3. 2 constructors, with varying levels of information set in each.
  4. 4 setters and 4 getters, one for each class attribute.
    • The setter for the static attribute Person.species, is also a static method.
  5. 2 public non-static methods
  6. 1 private non-static method.
One additional method we can add is the main() method

What is the Main Method?

In Java, the main method for any class is always declared as:

        
public static void main(String[] args) { }

The code inside the main method is what gets run when the class is compiled and run directly. This allows programs to have a singular starting point.

Since the main method is static, it is not related to a specific instance of the class, and thus cannot access or store instance variables and their related data. Instead, the main method can create new instances of their parent class type, and use those to store input data and call related methods.

For Example, all assignments you run via a Driver start at a main method. This is where relevant objects are created and methods are called to start reading input and printing output.

Most of the CS111 Assignments are also written inside and run through the main() method.

Below is an added main method for the above Person class, which creates two people and prints their information out.

And here is the output in the terminal when the Person class is compiled and ran.

How to use OOP?

To use Object oriented programming, you should decide how a problem can be grouped into repeatable tasks or similar information.

        i.e. Managing and storing information about multiple similar objects.

If repeated work has to be done, it can be stored and completed within distinct objects as well. Assignment 5 will see you complete a base set of work in the first task, followed by repeating that work in the following tasks for further analysis.

Classes can also be written for a problem itself, and then contain attributes and methods which can be used to solve that problem. Then, you can use other classes/libraries to store data while solving the problem. This is how you will complete much of Assignment 5: You will implement a graph data structure in the first class, then you will use it in the other classes to solve different problems.

Generally, until you understand why you need static methods/attributes, avoid using them.

By Colin Sullivan