Java - 使用另一个类的方法

时间:2016-10-30 22:25:21

标签: java

我有以下代码:

 interface Paint {
    float paintPerSurfaceUnit = (float) 0.3;
 }

 class PaintThings implements Paint {
    public float paint_sphere(Sphere obj){
        return (obj.area() * paintPerSurfaceUnit);
     }

  }

  class Sphere extends Shape {
    int radius;
    public float area(){
        return (float) (4*3.14*radius*radius);
    }
  }

我如何访问" paint_sphere"主要使用Sphere对象?

3 个答案:

答案 0 :(得分:1)

这里有两个选择:
要么使你的函数静态

class PaintThings implements Paint {
    static public float paint_sphere(Sphere obj){
        return (obj.area() * paintPerSurfaceUnit);
    }
}

并称之为

mySphere sphere = new Sphere();
PaintThings.paintSphere(yourSphere);

或者制作Paint的对象:

PaintThings myPainter = new PaintThings();
mySphere sphere = new Sphere();
myPainter.paint_sphere(mySphere);

答案 1 :(得分:0)

您必须使用PaintThings的实例。

public static void main(String[] args){
    Sphere sphere = new Sphere();
    PaintThings paintthings = new PaintThings();
    paintthings.paint_sphere(sphere);
}

确保将Sphere传递给paint_sphere(Sphere)方法。

答案 2 :(得分:0)

你可以尝试这个代码,方法paint实现PaintThings并通过这个传递对象Shape

  class Sphere extends Shape {
    int radius;
    public float area(){
        return (float) (4*3.14*radius*radius);
    }
    public float paint(){
        return new PaintThings().paint_sphere(this);
    }

但更好的方法是通过构造函数传递PaintThing对象以减少耦合

  class Sphere extends Shape {
    int radius;
    Paint paint;
    Sphere(Paint paint){
    this.paint = paint;
    }
    public float area(){
        return (float) (4*3.14*radius*radius);
    }
    public float paint(){
        return paint.paint_sphere(this);
    }