设计一个Shape接口和它的两个实现类Square和Circle 要求:Shape接口中有抽象方法getArea()和getgetPerimeter(),并定义sumArea()方法返回shape[] a中的面积之和
public class landb {
private static double sum;
static shape[] a;
abstract class shape{
public abstract double getArea();//面积
public abstract double getPerimeter();//周长
}
class Circle extends shape{
private double r;
public Circle(double r) {
this.r=r;
}
public double getArea() {
return Math.PI*r*r;
}
public double getPerimeter() {
return Math.PI*2*r;
}
}
class Rectangle extends shape{
private double x;
private double y;
public Rectangle(double x,double y) {
this.x=x;
this.y=y;
}
public double getArea() {
return x*y;
}
public double getPerimeter() {
return (x+y)*2;
}
}
public static double sumArea(shape[] a) {
for(int i=0;i<a.length;i++) {
sum+=a[i].getArea();
}
return sum;
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
double r1=input.nextDouble();
double r2=input.nextDouble();
double x1=input.nextDouble();
double y1=input.nextDouble();
double x2=input.nextDouble();
double y2=input.nextDouble();
//这里编译出错,因为静态方法无法调用动态方法
a[0]=new Circle(r1);
a[1]=new Circle(r2);
a[2]=new Rectangle(x1,y1);
a[3]=new Rectangle(x2,y2);
System.out.println(sumArea(a));
}
}
错误显示如下
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
No enclosing instance of type landb is accessible. Must qualify the allocation with an enclosing instance of type landb (e.g. x.new A() where x is an instance of landb).
这里因为main函数是由static修饰的,他是静态方法,而静态成员无法调用非静态成员;
这里解决方法有两个:
(1)将内部类定义为外部类(即放在当前类外去定义)
(2)经内部类定义为静态
这里示范一种:
将代码改为这样
abstract class shape{
public abstract double getArea();//面积
public abstract double getPerimeter();//周长
}
class Circle extends shape{
private double r;
public Circle(double r) {
this.r=r;
}
public double getArea() {
return Math.PI*r*r;
}
public double getPerimeter() {
return Math.PI*2*r;
}
}
class Rectangle extends shape{
private double x;
private double y;
public Rectangle(double x,double y) {
this.x=x;
this.y=y;
}
public double getArea() {
return x*y;
}
public double getPerimeter() {
return (x+y)*2;
}
}
public class landb {
private static double sum;
static shape[] a;
public static double sumArea(shape[] a) {
for(int i=0;i<a.length;i++) {
sum+=a[i].getArea();
}
return sum;
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
double r1=input.nextDouble();
double r2=input.nextDouble();
double x1=input.nextDouble();
double y1=input.nextDouble();
double x2=input.nextDouble();
double y2=input.nextDouble();
a[0]=new Circle(r1);
a[1]=new Circle(r2);
a[2]=new Rectangle(x1,y1);
a[3]=new Rectangle(x2,y2);
System.out.println(sumArea(a));
}
}