package com.yau;
public abstract class Shape {
public abstract void calArea();
public abstract void calPerimeter();
public class Rectangle extends Shape {
public double h;
public double w;
public Rectangle(double h, double w) {
this.h = h;
this.w = w;
}
public void calArea() {
System.out.println("Rectangle's area:" + h * w);
}
public void calPerimeter() {
System.out.println("Rectangle's perimeter" + 2 * (h + w));
}
}
public class Circle extends Shape {
public double r;
public Circle(double r) {
this.r = r;
}
public void calArea() {
System.out.println("Circle's area:" + r * r * Math.PI);
}
public void calPerimeter() {
System.out.println("Circle's perimeter:" + 2 * r * Math.PI);
}
}
public static void main(String[] args) {
Shape s1 = new Rectangle(8.2,2.8); //此处报错
s1.calArea();
s1.calPerimeter();
Shape s2 = new Circle(9.39); //此处报错
s2.calArea();
s2.calPerimeter();
}
}
1
choice4 2018-10-22 15:07:13 +08:00
main 是静态方法 非静态的东西拿到静态能直接用? 要么静态内部类 要么 main 构造实例
|
2
huangzhe8263 2018-10-22 15:32:22 +08:00 via Android
好消息好消息
本站成功和谷歌 百度达成合作关系,以后大家有什么想问的问题可以直接谷歌 百度搜索 不需要在站里问了,可以省下大家很多时间 |
3
TommyLemon 2018-10-22 15:36:58 +08:00
目测是声明与引用顺序的问题,把 Rectangle 和 Circle 分别单独写成一个文件试试
|
4
quinoa42 2018-10-22 15:51:45 +08:00
```
Temp.java:43: error: non-static variable this cannot be referenced from a static context Shape s1 = new Rectangle(8.2,2.8); //此处报错 ^ Temp.java:46: error: non-static variable this cannot be referenced from a static context Shape s2 = new Circle(9.39); //此处报错 ``` javac 不是都报了吗…… 简单的说,你的 rectangle 和 circle 是 inner class,关联的是单独的一个 shape instance 而不是 shape class 要过编译的话在 rectangle 和 circle 的声明行加上 static |