题目: 有图形接口Shape,参照圆Circle类补充完整正方形Square和三角形Triangle类,并分析运行结果。
interface Shape {
void draw();
void erase();
}
class Circle implements Shape {
void draw() { System.out.println(“Circle.draw()”);}
void erase() { System.out.println(“Circle.erase()”);}
}
class Square implements Shape {
void draw() { }
void erase() { }
}
class Triangle implements Shape {
void draw() { }
void erase() { }
}
public class Shapes {
public static Shape randShape() {
switch((int)(Math.random() * 3)) {
default: // To quiet the compiler
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
}
public static void main(String[] args) {
Shape[] s = new Shape[9];
// Fill up the array with shapes:
for(int i = 0; i < s.length; i++)
s[i] = randShape();
// Make polymorphic method calls:
for(int i = 0; i < s.length; i++)
s[i].draw();
}
}
package JavaExperiment2;
interface Shape {
public void draw();
public void erase();
}
class Circle implements Shape {
public void draw() { System.out.println("Circle.draw()");}
public void erase() { System.out.println("Circle.erase()");}
}
class Square implements Shape {
public void draw() {System.out.println("Square.draw()"); }
public void erase() {System.out.println("Square.erase()"); }
}
class Triangle implements Shape {
public void draw() {System.out.println("Triangle.draw()"); }
public void erase() { System.out.println("Triangle.erase()");}
}
public class Question5 {
public static Shape randShape() {
switch((int)(Math.random() * 3)) {
default: // To quiet the compiler
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
}
public static void main(String[] args) {
Shape[] s = new Shape[9];
// Fill up the array with shapes:
for(int i = 0; i < s.length; i++)
s[i] = randShape();
// Make polymorphic method calls:
for(int i = 0; i < s.length; i++){
s[i].draw();
s[i].erase();}
}
}
分析:各人有各人看法
写在后面:
高高山顶立 深深海底行。
附录:
命名规范
1、 类名、接口名首字母大写,如果类名、接口名由多个单词组成,每个单词的首字母都要大写。
2、 变量名、方法名首字母小写,如果名称由多个单词组成,每个单词的首字母都要大写。
3、 常量名全部大写