Question

I often read that abstract classes are only to use to extend them. I have a project in which I use abstract classes directly. For example a class which is responsible to capture a picture from the webcam stream:

import org.opencv.core.Mat;
import org.opencv.highgui.VideoCapture;

public abstract class Photographer {
    //create camera object
    static VideoCapture camera;
    static Mat image;
    public Photographer(){
        camera = new VideoCapture();
        image = new Mat();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //capture image
    public final static Mat capture() {

        camera.open(1);
        camera.read(image);
        camera.release();
        return image;
    }

}

My thought was, as this class only has one function and doesn't need any parameters, I could define it as abstract, so I don't have to make an instance of it, just to get a picture.

Is this a wrong idea of the use of abstract? How could I realize it the right way?

Thank you for any help.

derb

Was it helpful?

Solution 2

you are using your capture() method in a static way. static and abstract are totally unrelated concepts.

If you really wanted to deal with abstraction in this case, I would have something like this in the abstract class.

public Mat capture() {

    camera.open(1);
    camera.read(image);
    camera.release();

    implemenntCapature();

    return image;

}

public abstract implemenntCapture();

If you have WeddingPhotographer or WarPhotographer, then they can add their own behaviour to their implementCapture().

eg :

public void implementCapture() {
  addSoftfocus();
}
public void implementCapture() {
  duckBullets();
}

OTHER TIPS

The idea of abstract class is to represent some abstraction that has more detailed "versions". For example, "Car", "Vehicle", "Mechanism" can be the abstractions for Volkswagen Golf.

My thought was, as this class only has one function and doesn't need any parameters, I could define it as abstract

I think this is not a correct usage of abstract classes because of the reasons I wrote above - the class doesn't represent an abstraction for anything and not intended for extension.

Consider using abstract classes if any of these statements apply to your situation:

You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

For details of the same you can check this link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top