Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Software Engineering For Students: A Programming Approach Part 24. This fully revised version of Doug Bell's Software Engineering: A Programming Approach continues to use the successful formula of the previous editions. The author's approach is to present the main principles, techniques and tools used in software engineering, one by one, chapter by chapter. This book is a unique introduction to software engineering for all students of computer science and its related disciplines. It is also ideal for practitioners wishing to remain current with new developments in the area | 208 Chapter 15 Object-oriented programming exploit the common features of the classes. We do this by writing a class Sprite that embodies the commonality. This name is chosen because in computer games programs a sprite is the term for a graphical object. Here it is -------------------------- class Sprite protected int x y protected size public void moveLeft int amount x x - amount public void moveRight int amount x x amount 1 You can see that the variables and methods within this class are relevant to all the game objects. You will also notice that the variables declared at the head of the class that were described as public are now described as protected. This means that they are accessible from any subclasses as we shall see in a moment. We can now write class Alien so as to exploit the class Sprite as follows ------------------------------ class Alien extends Sprite private Imageicon alienimage public Alien int newX int newY int newSize x newX y newY size newSize alienimage new imageicon c alien.jpg public void display JPanel panel Graphics paper panel.getGraphics alienimage.painticon panel paper x y and you can see that this is now shorter than it was. The operative word in this code is extends. This is the Java keyword stating that class Alien inherits the features of class Sprite. All the public variables and methods become part of class Alien. The terminology is that Alien is a subclass of Sprite Sprite is the superclass of Alien Alien extends Sprite Sprite is the base class of Alien. 15.5 Polymorphism 209 Figure 15.2 Class diagram showing inheritance The relationships between classes are often shown in a UML class diagram such as Figure 15.2. Each class is shown as a rectangle. An arrow points from a subclass to a superclass. This diagram says that both Alien and Bomb are subclasses of Sprite. The variables x y and size are labeled protected rather than private. This means that they can be used within the subclass. But they are still inaccessible from .