Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 5 Object-Oriented Design Principles

Object Composition

You have learned how to define abstractions in the form of concrete classes, abstract classes, and interfaces. Individual abstractions offer certain functionalities that need to be combined with other objects to represent a bigger abstraction: a composite object that is made up of other smaller objects. You need to make such composite objects to solve real-life programming problems. In such cases, the composite object shares has-a relationships with the containing objects, and the underlying concept is referred to as object composition.

By way of analogy, a computer is a composite object containing other objects such as CPU, memory, and a hard disk. In other words, the computer object shares a has-a relationship with other objects.

Let’s recollect the FunPaint application in which you defined the Circle class. The class definition is given as follows:

public class Circle { private int xPos;

private int yPos; private int radius;

public Circle(int x, int y, int r) { xPos = x;

yPos = y; radius = r;

}

// other constructors elided ...

public String toString() {

return "mid point = (" + xPos + "," + yPos + ") and radius = " + radius;

}

// other members (suchas area method) are elided

}

In this simple implementation, you use xPos and yPos to define the center of a Circle. Instead of defining these variables as members of class Circle, let’s define a class Point, which can be used to define Circle’s center. Check the definition of Point class in Listing 5-2.

Listing 5-2.  Circle.java

// Point is an independent class and here we are using it with Circle class class Point {

private int xPos; private int yPos;

public Point(int x, int y) { xPos = x;

yPos = y;

}

public String toString() {

return "(" + xPos + "," + yPos + ")";

}

}

119

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]