- abstract class Geometry{
- public abstract double getArea(); }
- class Circle extends Geometry{
- double r;
- Circle(double r) {
- this.r=r;
- }
- public double getArea() {
- return 3.14*r*r;
- }
- }
- public class Student{
- public double calculate(Geometry g) {
- return g.getArea();
- }
- public static void main(String[]args) {
- Circle c=new Circle(3);
- Student s=new Student();
- System.out.println("The area of geometry is: "+s.calculate(c));
- }
- }
复制代码
*
*
*
*
*
以上代码重构,写成匿名内部类的
*
*
*
*
*
*- abstract class Geometry {
-
- public abstract double getArea(double r);
- }
- public class Student {
- public double calculate() {
- return new Geometry() {
- @Override
- public double getArea(double r) {
- return 3.14 * r * r;
- }
- }.getArea(2);
- }
- public static void main(String[] args) {
-
- Student s = new Student();
- System.out.println("The area of geometry is: " + s.calculate());
- }
- }
复制代码
这是我自己写的不知道对不对 |
|