Răzvan Andrei Macovei Răzvan Andrei Macovei - 1 month ago 8
Java Question

Java - use methods from another class

I have the following code:

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);
}
}


How can I access "paint_sphere" in main with Sphere object ?

Answer

You can try this code, the method paint instanciate the PaintThings and pass the object Shape via this

  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);
    }

but the better way is to pass the PaintThing object via the constructor

  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);
    }
Comments