我正在尝试运行以下简单代码,
public abstract class Shape{
abstract double area();
abstract double circumference();
public void show()
{
System.out.println("Area = "+area());
System.out.println("Circumference = "+circumference());
}
}
public class Circle extends Shape{
double r;
public double area()
{
return 3.14*r*r;
}
double circumference()
{
return 2*3.14*r;
}
Circle(double radius)
{
r=radius;
}
}
public class Rectangle extends Shape{
double x,y;
double area()
{
return x*y;
}
double circumference()
{
return 2*(x+y);
}
Rectangle(double length, double width)
{
x = length;
y = width;
}
}
public class Geometry
{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
Run Code Online (Sandbox Code Playgroud)
但我不断从Java编译器获得标识符预期错误.我究竟做错了什么.一切都是公开的,似乎没有语法错误.请帮忙.
这就是问题:
class Geometry
{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
Run Code Online (Sandbox Code Playgroud)
你的最终陈述没有声明变量 - 这只是一个陈述.这需要属于初始化块,构造函数或方法.例如:
public class Geometry {
public static void showCircle() {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这与继承无关 - 此代码将提供相同的问题:
class Test {
System.out.println("Oops");
}
Run Code Online (Sandbox Code Playgroud)