How Object-Oriented Programming Works

You can think of the Java programs you create as objects, just like physical objects that exist in the real world. Objects exist independently of other objects, interact in specific ways, and can be combined with other objects to form something bigger. If you think of a computer program as a group of objects that interact with each other, you can design a program that’s more reliable, easier to understand, and reusable in other projects.

In Hour 23, “Creating Java2D Graphics,” you create a Java program that displays pie graphs—circles with different-colored pie slices to represent data (see Figure 10.1). A pie chart is an object that is made up of smaller objects—individual slices of different colors, a legend identifying what each slice represents, and a title.

Figure 10.1. A Java program that displays a pie chart.

Image

Each object has things that make it different than other objects. Pie charts are circular, whereas bar graphs represent data as a series of rectangles. If you break down computer programs in the same way a pie chart is broken down, you’re engaging in OOP. In OOP, an object contains two things: attributes and behavior. Attributes are things that describe the object and show how it is different than other objects. Behavior is what an object does.

You create objects in Java by using a class as a template. A class is a master copy of the object that determines the attributes and behavior an object should have. The term class should be familiar to you because Java programs are called classes. Every program you create with Java is a class that you can use as a template for the creation of new objects. As an example, any Java program that uses strings is using objects created from the String class. This class contains attributes that determine what a String object is and behavior that controls what String objects can do.

With OOP, a computer program is a group of objects that work together to get something done. Some simple programs might seem as though they consist of only one object: the class file. However, even those programs are using other objects to get work done.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.107.40