java多态中的 找不到符号问题

来源:百度知道 编辑:UC知道 时间:2024/05/15 07:53:08
public class Shape{
public void draw(){}
public void p(){
System.out.println("here")
}
}
public class Square extends Shape{
public void draw(){
System.out.println("Square.draw()");
public void p(){
System.out.println("here is Triangle");
}
}

import java.util.*;
public class RandomShapeGenerator{
private Random rand = new Random(47);
public Shape next(){
switch(rand.nextInt(3)){
default:
case 0 : return new Circle();
case 1 : return new Square();
case 2 : return new Triangle();
}
}
}

public class Shapes{
private static RandomShapeGenerator gen = new RandomShapeGenerator();
public static void main(String[] args){
Shape[] s = new Shape[9];
for(int i = 0;i<s.length;i++)
s[i] = gen.next();
for(Shape shp : s)

for(Shape shp : s)
shp.draw();
shp.p();//超出了for语句范围,shp当然是找不到了~~

上面这段代码中的第三行超出了局部变量作用域了,请改成:
for(Shape shp : s) {
shp.draw();
shp.p();
}

如果没有花括号,那么for循环只能跟一个语句块!