开发者

Live method overrride

开发者 https://www.devze.com 2023-04-08 09:57 出处:网络
I\'m pretty new to Java and I\'m finishing my first project using it. Basically I read Head First Java and the API documentation for the classes I\'ve used so far. That\'s my Java background.

I'm pretty new to Java and I'm finishing my first project using it. Basically I read Head First Java and the API documentation for the classes I've used so far. That's my Java background.

This little piece of code rose a big little doubt on me, basically, what does this statement mean?

DataSource dataSource = new FileDataSource(tiffFile) {
    public String getContentType() {
 开发者_StackOverflow社区       return "image/tiff";
    }
};

Is it like a "live method override"? I still don't get what those brackets are doing there.

I'd really appreciate your help on this one.

Cheers.


What you've run across is an Anonymous Inner Class. There are many kinds of nested classes in Java and it would be beneficial for you to be familiar with all of them. I am including a link to a tutorial as a good starting point. Good luck!

Nested Classes in Java


It's called an Anonymous Inner Class. This creates a subclass of a FileDataSource with a call to the super contructor FileDataSource(tiffFile), in which the getContentType() method becomes overriden.

It can be rewritten as follows:

public static class TiffFileSource extends FileDataSource {
    public TiffFileSource(File file){
        super(file);
    }
    public String getContentType() {
        return "image/tiff";
    }
}

DataSource dataSource = new TiffFileSource(tiffFile);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号