Object Oriented Programming in Java

Aakash Sharma
The Startup
11 min readOct 24, 2019

--

In this article I plan on discussing how we can utilize the most popular & known programming language, Java. Java has grown & shaped many software's, web applications & continues to serve as a major inspiration for most programmers & programming languages. In this article, I plan on discussing important aspects of Java, what object oriented programming is & how it can be utilized in Java for real world examples. Java continues to become a popular interview topic & was my official 1st programming language I had learned. It led me into learning Python & C++ due to how amazing & robust these three programming languages really are.

Object oriented program refers to programming languages that use objects. The main aim of OOP is to bind together the data & the functions that operate on them so that no other part of the code can access this data except that function. Before we start coding, let’s understand some concepts!

Object oriented programming (OOP) is a different, but a related approach from procedural (structured) programming. We can break tasks into efficient sub-tasks & write re-usable methods to handle this! We use OOP to model the program on real world “things” & their interactions with other “things.” As we do this we can build larger & more complex programs, however it still requires use of “old” programming concepts (i.e. control structures, arrays, methods, etc.)

Remember we said that object oriented programming has to do with objects? Well it deals with something we call a “class.”

  • A class is a template or blueprint that defines the attributes (properties) & behaviors (methods) that an object of the class can have (ex: Student, Pencil, Vehicle, Button).
  • An object represents “an instance” or representation of a class (ex: Jack, Mary, Chris)

Remember! Each instance has the same attributes/properties (ex: color, radius, position) with potentially unique values. All objects of a class contain the same behaviors (ex: calculateArea, calculateTotalMiles, show, hide). We use camel case for establishing variables in Java where as we use snake case in Python.

How does this differ than procedural programming? We have to remember that procedural programming is very straight forward & a linear way of thinking. Most programs today rely on OOP concepts so procedural programming becomes more complicated to implement within software development. In data science, most of the Python packages rely on classes & objects built in that, so there’s a prime example of using OOP in another language.

OOP is advantageous because it’s easier to reuse code, increase an applications functionality & is easier to maintain while protecting (hiding) the data through encapsulation. According to Tutorialspoint, encapsulation in Java is a mechanism of wrapping the data (variables) & code acting on the data (methods) together as a single unit. This what makes OOP harder to understand because doing this becomes heavily time consuming.

When we want to establish constants, we make them in call capital letters (ex: MAX_ITEMS, MIN_HOUSES). We utilize different classes within Java as we do in Python & other programming languages. We have strings, integers, double, characters! Properties can contain mixed data types describing attributes or states of an object

  • Primitive data types (e.g. int, boolean, char, etc.)
  • Reference types (arrays, etc.)

Objects are created based on classes. We use the new operator to construct objects & give each object a unique name (like variables). Usually the class name is the same name as the constructor name!

https://www.google.com/search?hl=en&tbm=isch&source=hp&biw=1280&bih=631&ei=j5CwXfbdJOXn_Qa4lIjYDg&q=object+oriented+programming&oq=object+ori&gs_l=img.3.0.0l10.286.2170..3156...0.0..0.98.452.10......0....1..gws-wiz-img.p88irmuG2K0#imgrc=JWUDgSv_w6fPvM:

To better understand the OOP workflow let’s break this down even more into sub-tasks. An implementation (instantiation) of a class will create an object & each object will take on the properties/methods of the class, called instance variables & instance methods.

  • The object can be manipulated using methods taken on in the class
  • A class can be instantiated once per each object

So how does OOP work in Java? We create two .java files! File one is data associated to an object & associated behaviors. We call this the data definition class (DDC). We can end up having multiple of these but we shall cover that topic for other Java related fundamentals. File two is the usage of the data in a particular application. We use our DDC as a blueprint or shell for what we want to create & the 2nd file serves as a “connector” that creates traits that the object being created from the DDC, inherits! This is a concept we will cover throughout the rest of this article.

So where does OOP become useful? Imagine you have to create an object to represent a sports ball. What are the attributes/behaviors for this ball? Size, color, purpose, etc. Let’s see this in an example from a project I had done during my undergrad. I changed the scenario a bit to help simplify our goal.

Scenario: The Canadian football league (CFL) needs assistance tracking all teams within the league. However, since the commissioner has not yet worked with you, he wants you to prove yourself by building an initial solution that will track only one team within the league. More teams will be tracked later on. For each team, the league wants to track the name of the team & the number of players on the team.

For statistical analysis, the league wants to track the number of games the team has played & the total number of points scored across all games played. Note: If you are not familiar with football, during each game a team can score either no points or a number of points represented by a whole number (e.g. 3 points, 14 points, etc.).

We must construct an object-oriented solution that includes DDC to model one team & an accompanying implementation class to build one team. We will then track all points scored across games played.

Our Rules

  • DDC must also provide the ability to gather if the team has a faculty sponsor & the number of years the team has existed.
  • All teams are required to have a name & number of years the team has existed before the team can be created.
  • The number of players on the team may or not be provided when the team is created.
  • In the case the number of players on the team is not provided when the team is created, the number of players on the team must default to 17. In the case the number of players on the team is provided when the team is created, it may not exceed 19. However, after the team is created, if the number of players on the team changes, the new number of players on the team may not exceed 22.
  • The implementation class must instantiate & populate one team object using available details provided by the user.
  • Once the team object is created & populated, the solution should continuously prompt the user for the number of points scored in games the team has played, one game at a time, until the user has indicated they are finished entering games.

What you will need to do this problem:

  • A Java IDE or environment that allows you to write & compile Java code
  • Strong understanding of Java concepts

It seems at this point, the solution should print a well-formatted report, containing all available team details. Let’s start the DDC!

public class Team{//Creates a bunch a private constructors that allow hidden 
// functionailty of the implementation class
private String teamName;
private String teamSponsor;
private int numYears;
private int numPlayer;
private int numGames;
private int numPoints;
private static String nameTeam;


//Declares 2 static global variables that are constants
public static final int MIN_PLAYERS = 17;
public static final int MAX_PLAYERS = 22;


//Validates that the user enters a correct name for the team that
// can't be blank
public Team(String teamName){
if (teamName == null || teamName.equals("")){
throw new IllegalArgumentException("Team name cannot be blank");
}
this.teamName = teamName;
teamName += nameTeam;
}

//Mutators
public String getName() {return this.teamName;}
public String getSponsor() {return this.teamSponsor;}
public double getYears() {return this.numYears;}
public int getNumPlayer() {return this.numPlayer;}
public int getNumGames() {return this.numGames;}
public int getPoints() {return this.numPoints;}
public static String getNameOfTeams() {return nameTeam;}


//Validates that the sponsor name isn't blank
public void setSponsor(String teamSponsor){
if (!(teamSponsor == null) || (!teamSponsor.equals(""))){
this.teamSponsor = teamSponsor;
}
else {
throw new IllegalArgumentException(
"The sponsor name of the team is a problem");
}
}
//Validates the number of years, has to be greater than 0 to
//exist!
public void setNumYears(int numYears){
if(numYears > 0){
this.numYears = numYears;
}
else{
throw new IllegalArgumentException(
"The number of years of existence is incorrect");
}
}

//Validates the number of players on a team, the number of players //can't go over 22 & can't be under 17
public void setNumPlayer(int numPlayer){
if (numPlayer >= MIN_PLAYERS && numPlayer <= MAX_PLAYERS){
this.numPlayer = numPlayer;
}
else {
throw new IllegalArgumentException(
"The number of players entered is incorrect, should be between: " + MIN_PLAYERS + " & " + MAX_PLAYERS);
}
}

//Validates the number of games, a team has to play 1 least one game
public void setNumGames(int numGames){
if (numGames > 0){
this.numGames = numGames;
}
else {
throw new IllegalArgumentException("The number of games entered is incorrect");
}
}

//Validates the number of points, can be 0 because a team could score no points in a season
public void setPoints(int numPoints){
if (numPoints >= 0){
this.numPoints = numPoints;
}
else {
throw new IllegalArgumentException("The number of points entered is incorrect");
}
}

//Groups the attributes of the object together to print out the object
public String toString(){
return this.getName() + " has "
+ this.getSponsor() + " as team sponsor " + " with "
+ this.getNumPlayer() + " players "+ " with "
+ this.getNumGames() + " games played "+ " with "
+ this.getPoints() + " total points for that season ";
}

}

When we talking about these files communicating with each other we’re talking about methods, with the information “in” being parameters & the information “out”, our data being return values! Let’s create the implementation class that will be talking to our DDC. I will denote what the code does within “//” meaning that it is a comment about what those line(s) of code do or does. We denote comments in Java with two “//” or “/* */” for paragraphs of comments.

import javax.swing.JOptionPane;
public class teamInformation {
public static void main (String[] args) {

//Allows the user to continuously create a team object as long as
//the team attributes are true
//It will re-prompt them to enter another team if they would like
//too
String teamInfo = "";

do{
try{
Team aTeam = addTeam();
teamInfo += aTeam.toString() + "\n";
printTeamReport(aTeam);
}catch(IllegalArgumentException e){
JOptionPane.showMessageDialog(null, "Team could not be created! " + e.getMessage());
}
}while(JOptionPane.showInputDialog("Enter another team? Enter Y or N").equalsIgnoreCase("Y"));
}

//The method that creates a team object, allowing the user to enter information about the team
public static Team addTeam(){

Team aTeam = new Team(JOptionPane.showInputDialog("Enter the name of the team: "));

//Allows the user to enter the name of the sponsor for the team
boolean sponsorSet = false;
do{
try{
aTeam.setSponsor(JOptionPane.showInputDialog("Enter the sponsor name: "));
sponsorSet = true;
}catch(IllegalArgumentException e){
JOptionPane.showMessageDialog(null, "Sponsor name couldn't be set. " + e.getMessage());
}
}while(!sponsorSet);

//Allows the user to enter the age of the team, how long it has
// existed
boolean yearSet = false;
do{
try{
aTeam.setNumYears(Integer.parseInt(JOptionPane.showInputDialog("Enter the age of the team: ")));
yearSet = true;
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Can't be letters. ");
}catch(IllegalArgumentException e){
JOptionPane.showMessageDialog(null, "Age of the team couldn't be set. " + e.getMessage());
}
}while(!yearSet);

//Allows the user to enter the number of players
boolean playerSet = false;
do{
try{
aTeam.setNumPlayer(Integer.parseInt(JOptionPane.showInputDialog("Enter the number of players on the team between 17 & 22:")));
playerSet = true;
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Can't be letters. ");
}catch(IllegalArgumentException e){
JOptionPane.showMessageDialog(null, "Number of players couldn't be set. " + e.getMessage());
}
}while(!playerSet);

//Allows the user to enter the total number of games
boolean gameSet = false;
do{
try{
aTeam.setNumGames(Integer.parseInt(JOptionPane.showInputDialog("Enter the number of total games: ")));
gameSet = true;
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Can't be letters. ");
}catch(IllegalArgumentException e){
JOptionPane.showMessageDialog(null, "Number of total games couldn't be set. " + e.getMessage());
}
}while(!gameSet);
//Allows the user to enter the total number of points
boolean pointSet = false;
do{
try{
aTeam.setPoints(Integer.parseInt(JOptionPane.showInputDialog("Enter the total number of total points for the total number of games:")));
pointSet = true;
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Can't be letters. ");
}catch(IllegalArgumentException e){
JOptionPane.showMessageDialog(null, "Number of total points couldn't be set. " + e.getMessage());
}
}while(!pointSet);
//This will return the the attributes of the team to be stored in
//the team object
//Team name, sponsor name, age of the team, number of players,
// number of total games, number of total points
return aTeam;
}
//Prints out a report for the team information
public static void printTeamReport(Team aTeam){
JOptionPane.showMessageDialog(null, "The team information\n"
+ aTeam.toString());
}
}

So what is actually going on here? We’ve created the blueprint class that will generate our objects or types, in this case, our teams. Our implementation class is creating the features for our teams, such as name, team size, team age, etc. What else? Our DDC keeps variables that store the data “hidden” (private) which allows the class to define & control data validity. Our methods that belong only in the class are also declared private. The DDC will share information with the application upon request, making it available (public), while hiding the implementation details (encapsulation).

Why do this? Access to data must be protected from accidental update which ensures only one class has ability to update data. It allows responsibility for data validation which lies with the DDC before storing the values. The implementation must deal with the result of the validation, since that is where the request to store the data, is occurring.

There are four categories of behavior (methods) we utilized in this scenario:

  • Constructor — defined statements to be execute when an object of the class is created.
  • Accessor (get) methods — returns value of an attribute to an external class
  • Mutator (set) methods — change the value of an attribute based on information given by an external class

Some of the key fundamentals we focus on in this example as well as in other OOP scenarios are polymorphism & inheritance. These are key to understand no matter what programming language you’re utilizing.

Polymorphism refers to the fact you can have different sub-classes as objects of a single super-class. We automatically select the proper method to apply based on the subclass it belongs to. Polymorphism allows objects to change & take the form of different objects.

Another fundamental topic is inheritance. Inheritance is a conceptualized as a hierarchy making up of one class where the sub-class, or child class inherits properties & behavior from another class (super-class). We didn’t use polymorphism or inheritance because we only had 1 class. Multiple classes would allow us to dive deeper into this.

That concludes this article. I briefly touched on the fundamentals of OOP principles & techniques. I will in the future provide more examples of which involve polymorphism & inheritance. Thank you for taking the time to read this article. If you have any further input, please provide it in the comments.

--

--

Aakash Sharma
The Startup

Data Scientist & Analyst | Cybersecurity Network Engineer | Full Stack Software Developer | Aspiring Systems Engineer | Machine Learning & A.I. Enthusiast