<< Chapter < Page Chapter >> Page >

Here is an example of how we use AreaCalc to compute area of a rectanglee of width 4.5 and height 7.2. In the Interactions pane of DrJava, enter the following lines of code. AreaCalc calc = new AreaCalc(); calc.rectangle(4.5, 7.2) The first line of code defines calc as a variable of type AreaCalc and assign to it an instance of the class AreaCalc . new is a keyword in Java. It is an example of what is called a class operator. It operates on a class and creates an instance (also called object ) of the given class. The second line of code is a call to the object calc to perform the rectangle task where width is assigned the value 4.5 and height is assigned the value 7.2. To get the area of a 5.6 by 8.4 rectangle, we simply use the same calculator calc again: calc.rectangle(5.6, 8.4); So instead of solving just one proble -given a rectangle 4.5 ft wide and 7.2 ft high, compute its area- we havebuilt a "machine" that can compute the area of any given rectangle. But what about computing the area of a right triangle with height 5 and base 4? We cannot simply use this calculator. We need another specialized calculator, the kind that can compute the area of a circle.

There are at least two different designs for such a calculator.

  • create a new class called AreaCalc2 with one method called rightTriangle with two input parameters of type double . This corresponds to designing a different area calculator with one button labeled rightTriangle with two input slots.
  • add to AreaCalc a method called rightTriangle with two input parameters of type double . This corresponds to designing an area calculator with two buttons: one labeled rectangle with two input slots and the other labeled rightTriangle , also with two input slots.
In either design, it is the responsibility of the calculator user to pick the appropriate calculator or press the appropriate button on the calculator to correctly obtain the area of the given geometric shape. Since the two computations require exactly the same number of input parameters of exactly the same type, the calculator user must be careful not get mixed up. This may not be too much of an inconvenience if there are only two kinds of shape to choose from: rectangle and right triangle. But what if the user has to choose from hundreds of different shapes? or better yet an open-ende number of shapes? How can we, as programmers, buid a calculator that can handle an infinite number of shapes? The answer lies in abstraction . To motivate how conceptualize the problem, let us digress and contemplate the behavior of a child!

Modeling a person

For the first few years of his life, Peter did not have a clue what birthdays were, let alone his own birth date. He was incapable of responding to your inquiry on his birthday. It was his parents who planned for his elaborate birthday parties months in advance. We can think of Peter then as a rather "dumb" person with very little intelligence and capability. Now Peter is a college student. There is a piece of memory in his brain that stores his birth date: it's September 12, 1985! Peter is now a rather smart person. He can figure out how many more months till his next birthday and e-mail his wish list two months before his birth day. How do we model a "smart" person like Peter? Modeling such a person entails modeling

  • a birth date and
  • the computation of the number of months till the next birth day given the current month.
A birth date consists of a month, a day and a year. Each of these data can be represented by an integer, which in Java is called a number of type int . As in the computation of the area of a rectangle, the computation of the number of months till the next birth day given the current month can be represented as a method of some class. What we will do in this case that is different from the area calculator is we will lump both the data (i.e. the birth date) and the computation involving the birth date into one class. The grouping of data and computations on the data into one class is called encapsulation. Below is the Java code modeling an intelligent person who knows how to calculate the number of months before his/her next birth day. The line numbers shown are there for easy referencing and are not part of the code. 1 public class Person { 2 /**3 * All data fields are private in order to prevent code outside of this 4 * class to access them.5 */ 6 private int _bDay; // birth day7 private int _bMonth; // birth month; for example, 3 means March. 8 private int _bYear; // birth year9 /**10 * Constructor: a special code used to initialize the fields of the class. 11 * The only way to instantiate a Person object is to call new on the constructor.12 * For example: new Person(28, 2, 1945) will create a Person object with 13 * birth date February 28, 1945.14 */ 15 public Person(int day, int month, int year) {16 _bDay = day; 17 _bMonth = month;18 _bYear = year; 19 }20 /**21 * Uses "modulo" arithmetic to compute the number of months till the next 22 * birth day given the current month.23 * @param currentMonth an int representing the current month.24 */ 25 public int nMonthTillBD(int currentMonth) {26 return (_bMonth - currentMonth + 12) % 12; 27 }28 } ( Download the above code ) We now explain what the above Java code means.
  • line 1 defines a class called Person. The opening curly brace at the end of the line and the matching closing brace on line 28 delimit the contents of class Person. The key word public is called an access specifier and means all Java code in the system can reference this class.
  • lines 2-5 are comments. Everything between /* and */ are ingored by the compiler.
  • lines 6-8 define three integer variables. These variables are called fields of the class. The key word private is another access specifier that prevents access by code outside of the class. Only code inside of the class can access them. Each field is followed by a comment delimited by // and the end-of-line. So there two ways to comment code in Java: start with /* and end with */ or start with // and end with the end-of-line.
  • lines 9-14 are comments.
  • lines 15-19 constitute what is called a constructor . It is used to initialize the fields of the class to some particular values. The name of the constructor should spell exactly like the class name. Here it is public , menaing it can be called by code outside of the class Person via the operator new. For example, new Person(28, 2, 1945) will create an instance of a Person with _bDay = 28, _bMonth = 2 an d_bYear = 1945.
  • lines 20-24are comments.
  • line 23 is a special format for documenting the parameters of a metod. This format is called the javadoc format. We will learn more about javadoc in another module.
  • lines 25-27 constitute the definition of a method in class Person.
  • line 26 is the formula for computing the number of months before the next birthday using the remainder operator %. x % y gives the remainder of the integer division between the dividend x and the divisor y.

Practice Key Terms 6

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Principles of object-oriented programming. OpenStax CNX. May 10, 2013 Download for free at http://legacy.cnx.org/content/col10213/1.37
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?

Ask