Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
COMP5028 Object Oriented Analysis and Design  Semester 1, 2007 
 1
 
 
Laboratory session Six  
SIT Lab 116/117 
Wednesday May 2, 2007 
School of Information Technologies 
The University of Sydney 
 
 
 
Objective 
• Understand the two reuse mechanism – delegate vs. inheritance 
ƒ Practicing both options 
ƒ Understand the differences. 
• Practice using Adapter pattern. 
Tasks 
Suppose we have a Rectangle class with the following API specification: 
Class Rectangle 
java.lang.Object 
  Rectangle 
 public class Rectangle 
extends java.lang.Object 
The Rectangle class defines a geometry Rectangle and methods of calculating geometry 
facts  
 
Constructor Summary 
Rectangle()  
          default constructor creates a Rectangle of width 4 and height 2  
Rectangle(int width, int height)  
          create a Rectangle with given width and height  
   
Method Summary 
 int area()  
          get the area of a Rectangle 
 int getHeight()  
          retrieves the height of a Rectangle 
 int getWidth()  
COMP5028 Object Oriented Analysis and Design  Semester 1, 2007 
 2
          retrieves the width of a Rectangle 
 int perimeter()  
          get the perimeter of a Rectangle 
 void setHeight(int h)  
          set the height of a Rectangle 
 void setWidth(int w)  
          set the width of a Rectangle 
 
   
1. Create a Square class through reusing the Rectangle class. You need to 
practice both delegation and inheritance options. 
2.  Suppose we want to reuse Rectangle class as a Shape in the following 
application. How can you achieve it? 
 
interface Shape{ 
 int getPerimeter(); 
 String getName(); 
 int getArea(); 
} 
 
class Circle implements Shape{ 
 int r; 
 public Circle(int r){ 
  this.r = r; 
} 
 
 public int getPerimeter(){ 
  return (int) 3.14 * 2 * r; 
}  
 
public int getArea(){ 
 return (int) 3.14 * r * r; 
} 
 
public String getName(){ 
 return “circle:” + r; 
} 
} 
 
class ShapeCollection{ 
 Shape[] shapes = new Shape[20]; 
 … 
 void printArea(){ 
  for (int i = 0; i < shapes.length; i++){ 
System.out.println(shape[i].getName()+ ": " + 
shape[i].getArea()); 
  }    
 } 
 …   
}