简体   繁体   中英

Java workaround for subclass forced to call super() in constructor?

I am editing a program that uses a RandomAccessFile object, and I want to come up with my own RandomAccessFile class that uses a different source for the data other than a file object (it's an Amazon webservices S3 object, but that's irrelevant)

I want to basically make a class called RandomAccessS3 that has RandomAccessFile as its superclass, so I can simply say

RandomAccessFile raf = new RandomAccessS3();

and therefore keep the existing code the same. I will simply override every method in RandomAccessFile.

The problem is that in the subclass RandomAccessS3's constructor I am forced to call RandomAccessFile's constructor using super(file, mode) which takes as parameter a filename, and throws an error and dies if the file is invalid.

I can't surround the super() call with a try/catch block because super is required to be the first line in the constructor. I could supply a dummy file, but I don't want to force the user to do that. Is there any simple way around this?

Thanks!

well, you can actually set a name attribute or something on the super class. And in constructor of that class, set the value of the String passed in to the name instance variable belonging on that class.

This way all derivatives must pass in something while instantiating child instances and the value passed is deferred to the parent class. This way you can force super() to always be called in derivatives.

There's no simple way around this. The constructor is there to make sure that an instance is in a good/valid state, and part of the contract of RandomAccessFile is that an instance is linked to a valid file.

As a huge hack, I suppose that you could create a temp file, just to satisfy the RandomAccessFile constructor.

A better approach probably is to create a new interface and update your references from RandomAccessFile to the new interface. Then, implement the interface twice, once using RandomAccessFile and once with S3 calls.

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