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?



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.

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.

Need Your Help

Malayalam font in Nokia E63

mobile symbian nokia

I need to install Malayalam font(which is foreign language) on my E63.

SOAP Request with Globe LBS API

java xml api soap request

I'm still new to SOAP and I have trouble resolving this issue.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.