Think Java, Chapters 11 and 14: How to Think Like a Computer Scientist, Classes and How to Think Like a Computer Scientist, Objects or objects by Allen Downey and Chris Mayfield.
Safari, Deitel Classes and Objects Video
Chapter 11.10 and Chapter 14.8 of ThinkJava
Object oriented programming allows us to program in a style that can result in code that is suitable for large scale software development projects. In this chapter, we will learn how to create a class, how to instantiate an object, the difference between static and non-static methods, visibility specifiers, and explore a simple program that utilizes more than two classes.
Sometimes it is useful to group related data and functions into one class. By combining these two, we can often simplify programming in many ways. This representation of data and functions into one is called a class. A running copy of this representation is called an Object. The data that is part of an object is called member variables and the functions are called methods. Member variables are made up of class and instance variables. See Methods to learn about class and instance variables in detail.
Here is an example of a Class in Java.
public class Employee { private String name; private int rank; public Employee(String name, int rank) { this.name = name; this.rank = rank; } public int getVacationDays() { if( rank == 1 ) { return 14; } else if ( rank == 2 ) { return 10; } else { return 7; } }
Almost everything in Java is an object except primitives such as short, int, doubles, char, long and boolean. For example, strings and arrays are examples of objects that we have been using frequently in Java. The new keyword is used to create an object in Java. When creating a class, it is important to make sure that the contents of a class show high cohesion. For example, in the Employee class, all the member variables and methods should be about employees. If a method such as sendChatMessage() which sends a chat message to a coworker would be out of place an lessen the cohesion of the class.
Employee bob = new Employee("Bob",1);
When you create an object using the new keyword, a special method called the constructor is executed. The constructor is used to initialize instance variables and prepare the object which is created in a special space in memory called the heap. The constructor’s name and the class name have to match. If a constructor is not present in the class, class, a default constructor is provided instead. The default constructor has no parameters and initializes member variables as follows: numeric primitives to 0, booleans to false, char to ‘/u0000’ and reference variables to null. When any constructor is created, the default constructor no longer exists. Constructors with different method signatures (constructor overloading) are allowed.
The following is the no argument constructor:
public Employee() { }
The no argument constructor could be used to set default values such as the following:
public Employee() { name = "Bob"; rank = 1; }
The default constructor does not initialize member variables in a meaningful way so a constructor with parameters can be useful.
public Employee(String name, int rank) { this.name = "Bob"; this.rank = 1;
In the above constructor, we see the this keyword for the first time. The this keyword is a reference to the current object and it can be used to refer to the instance variables of the current object. The this keyword can also be used to call other constructors in the following manner.
public Employee() { this("Bob",1); }
For more information about the this keyword, you can read more about it in the Java Tutorial
Information hiding refers to the idea that member variables of a class should be closed for modification from outside of class to prevent unintentional or intentional modification and prevent complexity arising from such unexpected modifications. In Java, the public, private, and protected keywords are used to control access to member variables and methods of a class. You can refer the Java tutorial to learn the details but the public keyword indicates that you can access the variable or method from anywhere and the private keyword indicates that you can access them from only the class.
You can use getters to access private member variables. Getters refer to methods that return the value of private member variables and the convention is to name such methods with the prefix get. Here is an example from Employee class.
public class Employee { public String getName() { return name; } public int getRank() { return rank; } }
Setters are methods that are used to change the value of private member variables. The convention is to name setters with the prefix set. Here is an example from the Employee class.
public class Employee { public void setName(String name) { this.name = name; } public void setRank(int rank) { this.rank = rank; } }
Instance methods are methods that belong to each object but static methods are methods that belong to a class. For example, the sort() method in the Collection class is an example of a static method. Utility methods such as the sort() method do not need to be included with each object so they are part of a class. In fact, the main() method is an example of a static method.
In object-oriented programming, it is important not to overuse static methods. When static methods are overused, the programming style can resemble the procedural programming style more than the object-oriented style. At the beginning of your journey in object-oriented programming, try to minimize the creation and use of static methods in your classes. There is also a memory footprint problem with the overuse of static variables and static methods. This will be covered in ITEC 2150 when you learn about garbage collection. Please see the Methods chapter for more information about static and instance methods.
When using a String in Java, it was necessary to use the equals method to establish the equality of two objects.
String str = "java rocks"; if ( str.equals("Java Rocks") ) { System.out.println("true!"); }
The reason is because strings in Java are objects and you cannot use the == operator to test equality. To use the equals() method to test equality, it is necessary to implement the equals() method. The following is equals() method for the Employee class shows that two Employee objects are equal if the name is equal (this is somewhat unrealistic in the real world).
public boolean equals(Object obj) { if (obj instanceof Employee) { return name.equals((Employee)obj.getName()); } else { return false; } }
Sometimes it is necessary to get the string representation of an object. In Java, the toString() method is used to get the string representation of an object. For the Employee class, we can represent the Employee object with the name and rank properties.
public String toString() { return name + " " + rank; }
If you implement the toString() method, you can use it in the System.out.println() method to print the string representation of the object.
Employee e = new Employee("Bob",1); System.out.println(e);
Suppose you have a Leadership class which holds an ArrayList of employees that are managers.
public class Leadership { private ArrayList<Employee> managers; public Leadership() { managers = new ArrayList<Employee>(); } public void addManager(Employee e) { managers.add(e); } }
You can see that an object (ArrayList of employees) can be part of another object (Leadership). In object-oriented programming, we call this relationship a has-a relationship. Object-oriented programming focuses on such relationships among objects and the communication among them.
Create a simple class named student with the following properties:
Also, create the following methods:
Two students objects are considered equal if their id is the same. The toString() method should print out the name and id of the object.
Create a class called School that holds an ArrayList of students. Create the following methods for the class.