<< 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.

Questions & Answers

A golfer on a fairway is 70 m away from the green, which sits below the level of the fairway by 20 m. If the golfer hits the ball at an angle of 40° with an initial speed of 20 m/s, how close to the green does she come?
Aislinn Reply
cm
tijani
what is titration
John Reply
what is physics
Siyaka Reply
A mouse of mass 200 g falls 100 m down a vertical mine shaft and lands at the bottom with a speed of 8.0 m/s. During its fall, how much work is done on the mouse by air resistance
Jude Reply
Can you compute that for me. Ty
Jude
what is the dimension formula of energy?
David Reply
what is viscosity?
David
what is inorganic
emma Reply
what is chemistry
Youesf Reply
what is inorganic
emma
Chemistry is a branch of science that deals with the study of matter,it composition,it structure and the changes it undergoes
Adjei
please, I'm a physics student and I need help in physics
Adjanou
chemistry could also be understood like the sexual attraction/repulsion of the male and female elements. the reaction varies depending on the energy differences of each given gender. + masculine -female.
Pedro
A ball is thrown straight up.it passes a 2.0m high window 7.50 m off the ground on it path up and takes 1.30 s to go past the window.what was the ball initial velocity
Krampah Reply
2. A sled plus passenger with total mass 50 kg is pulled 20 m across the snow (0.20) at constant velocity by a force directed 25° above the horizontal. Calculate (a) the work of the applied force, (b) the work of friction, and (c) the total work.
Sahid Reply
you have been hired as an espert witness in a court case involving an automobile accident. the accident involved car A of mass 1500kg which crashed into stationary car B of mass 1100kg. the driver of car A applied his brakes 15 m before he skidded and crashed into car B. after the collision, car A s
Samuel Reply
can someone explain to me, an ignorant high school student, why the trend of the graph doesn't follow the fact that the higher frequency a sound wave is, the more power it is, hence, making me think the phons output would follow this general trend?
Joseph Reply
Nevermind i just realied that the graph is the phons output for a person with normal hearing and not just the phons output of the sound waves power, I should read the entire thing next time
Joseph
Follow up question, does anyone know where I can find a graph that accuretly depicts the actual relative "power" output of sound over its frequency instead of just humans hearing
Joseph
"Generation of electrical energy from sound energy | IEEE Conference Publication | IEEE Xplore" ***ieeexplore.ieee.org/document/7150687?reload=true
Ryan
what's motion
Maurice Reply
what are the types of wave
Maurice
answer
Magreth
progressive wave
Magreth
hello friend how are you
Muhammad Reply
fine, how about you?
Mohammed
hi
Mujahid
A string is 3.00 m long with a mass of 5.00 g. The string is held taut with a tension of 500.00 N applied to the string. A pulse is sent down the string. How long does it take the pulse to travel the 3.00 m of the string?
yasuo Reply
Who can show me the full solution in this problem?
Reofrir Reply
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply
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