简体   繁体   中英

Initialize a Class, if it it has in its constructor an Interface as a Parameter?

There is a Class called TrianglePictureFilter, which has a the following constructor:

public TrianglePictureFilter(IPointGenerator pointGenerator) {
        super(pointGenerator);
    }

IPointGenerator is an interface:

import java.awt.Point;

/**
 * Point generator interface, providing points for generating geometric primitives.
 */
public interface IPointGenerator {
    /**
     * Generates the next (random) point.
     * 
     * @return a new point
     */
    public Point nextPoint();
}

I would like to use one of the methods of TrianglePictureFilter in another class, I have imported it, but I do not know how to initialize it, or to be more precise how to initialize the parameter in the constructor. Can somebody help me with that?

So, if you have not already implemented your IPointGenerator class, you would do it like this:

public class TrianglePictureFilter implements IPointGenerator {

    public Point nextPoint() {
        // Return your random point.
    }

}

I'm not sure if this exactly what you were asking for, but to use this code, it would be as simple as this:

TrianglePictureFilter filter = new TrianglePictureFilter();
Point randomPoint = filter.nextPoint();

Is this the kind of behavior you were looking for? If not, you probably don't want to use an interface .

An object must inherit the IPointGenerator interface like so:

class AClass: IPointerGenerator {

 public Point nextPoint()
 {
       //do some action here to return a point

 }

}

//Once that is done

AClass = new AClass(); // which can be passed into that constructor. This should be enough to get you started.

您可以在Java 8中使用default关键字。

You could use an anonymous class declaration when you instantiate the class. new TrianglePictureFilter(new IPointGenerator { public Point newPoint{ // do something }});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM