我遇到了一些麻烦。此代码不会引发任何编译时错误,但System.out.println
不会显示。它应该显示您应该如何为所有四个面着色。我在 for 循环中犯了错误还是与结构有关?
请参见下面的代码:
public interface Colorable {
// Abstract to be called later
public abstract String howToColor();
}
public class HowToColour {
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
public class TestColorable {
public static void main(String[] args) {
Object[] obj1 = {
new Square(),
new Rectangle(),
new Rhombus(),
new Parallelogram(),
new Trapezium()
};
for (int i = 0; i < obj1.length; i++) {
if (obj1[i] instanceof Colorable) {
System.out.println(((Colorable) obj1[i]).howToColor());
} else {
System.out.println("This shape is not to be colored");
}
}
}
}
class GeometricOgject {
}
// Initial Method to use the interface
class Square extends GeometricOgject implements Colorable {
@Override
public String howToColor() {
return "Square: Color all four sides";
}
}
// Method to use an interface in an abstract class
abstract class FourSides implements Colorable {
}
class Rectangle extends FourSides {
@Override
public String howToColor() {
return "Rectangle: color all four sides";
}
}
class Rhombus extends FourSides {
@Override
public String howToColor() {
return "Rhombus: color all four sides";
}
}
class Parallelogram extends FourSides {
@Override
public String howToColor() {
return "Parallelogram: color all for sides";
}
}
class Trapezium extends FourSides {
@Override
public String howToColor() {
return "Trapezium: color all four sides";
}
}