<< Chapter < Page Chapter >> Page >

Object-oriented systems use classes to express the above notions of abstract equivalence.

A class is an abstract description of a set of objects.
A class thus contain the descriptions of all the behaviors of the objects that it represents. In computer science parlance, we call the individual behaviors of a class its methods . In addition, a class may, but not always, contain descriptions of the internal data held by the objects, called its fields , as well as implementation details about its methods and fields.

Turning the description around, we can say that a class is a template or recipe for the creation of a particular type of object. That is, one can use a class to create (" instantiate ") objects of the type described by the class. Be careful not to make the very beginner's common mistake of equating classes and objects. A class is a specification of an set of objects, it is not the actual object.

In technical terms, a class defines a new type    in the system. Types are identifies used to differentiate different kinds of data. For instance, integers, characters, strings and arrays are all types of data.

Implementation in java

Classes are the fundamtental building blocks of Java programs. Defining a class is basically a matter of specifying a name for the class, its relationship to other classes and what sort of behaviors the class exhibits as well as what data it may contain.

SuppSuppose we wanted to define a class to describe a household pet. We could do it as such: class Pet { }

The word class above is called a keyword and can only be used to state that the following code is the definition of a class. The class keyword is immediately followed by the desired name of the class, Pet here. The curly braces, {...} , indicate the extent of the definition of the class. That is, any definitions of the class's behaviors and data will be found between the curly braces. Curly braces must therefore always appear as a matched set.

In general, in Java, curly braces mark the extent of a definition.

The accepted typographic standard in the Java community is that the opening curly brace is at the end of a line and the ending curly brace is at the beginning of its own line. Any code between the curly braces is indented.

Well, our class for pets is simple, but not very interesting because it doesn't do anything. We could say that our pet has a name, but personally, I have found that the behavior of most pets is not affected by the particular name we give them. That is, we can give our pet a name but that doesn't change the way they behave. Let's try something else.

Pets eat a certain amount of food per day. Pets have a certain weight. Let's create a model , that states that the number of hours that a pet sleeps per day is related to the amount of food they eat and their weight. Thus we could say that a pet has a behavior of sleeping a certain number of hours depending on its weight and the amount of food eaten.

/** * A class that models a household pet*/ class Pet{/*** The weight of the pet in lbs */double weight;/** * The number of hours the pet will sleep after eating* the given lbs of food. * @param lbsOfFood The number of lbs of food eaten.* @return The number of hours slept after eating the food. */double hoursSlept(double lbsOfFood) { return 24.0*lbsOfFood/weight;} }

But what about the pet's owner (a person, supposedly)? A person is not such a simple thing as a weight. Assigning a number to every possible person in the world is possible but not necessarily the most practical technique. There are many ways to represent people: the Registrar likes to think of you as a number with credit hours and unpaid bills, The CS department sees you as a 8-character login and unfinished graduation requirements, your doctor sees you as a collection of pulsating blood vessels, cells and bones, and your parents see you as this sweet little thing just out of diapers. A person is still a person, but the way that we choose to represent them may differ from situation to situation.

But here's the crux of the issue: does your pet care how you are internally represented? Or does your pet just want something that is a person to be their owner? /** * A class that models a household pet*/ class Pet{/*** The weight of the pet in lbs */double weight;/** * The pet's owner*/ Person owner;/*** The number of hours the pet will sleep after eating * the given lbs of food.* @param lbsOfFood The number of lbs of food eaten. * @return The number of hours slept after eating the food.*/ double hoursSlept(double lbsOfFood) {return 24.0*lbsOfFood/weight; }/*** Determines whether or not this pet is happy to see a * particular person.* @param p The person who the pet sees. * @return true if the Person is their owner, false otherwise.*/ boolean isHappyToSee(Person p) {return p == owner; }}

Here we've added a field of type Person , which is a class used to represent people. It doesn't matter how Person is implemented, just that it is a representation of a person. We could use the class definition of Person that was created in the module on Abstraction , or perhaps one that is fixed up a little bit, or perhaps a completely new one. The Pet doesn't care.

Thus we see that objects can contain objects. What does this say about the possible complexity of a system of objects?

Download code

To download a zipped file containing the code above, click one of the following links:

Both of the above codebases include a DrJava project file (.pjt) that can be opened from DrJava to easily manage all the code and test files.

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 2

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