Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use extended class in place of base class

Java 1.6. I have extended a class to include some methods. Now I would like to use the extended class in place of the base class. However, the classes that could use the base class cannot "recognize" the extended class. What is the (recommended) fix?

I know this has been asked many times in different flavors, but I can't get it!

Example- Extend class SAMRecord and use SAMRecordExt afterwords:

public class SAMRecordExt extends SAMRecord{

    public SAMRecordExt(SAMFileHeader header) {
        super(header);
    }       

}

Now, while this works:

SAMRecord rec= sam.iterator().next();

This gives me a compilation error

SAMRecordExt recext= sam.iterator().next();
>>> Type mismatch: cannot convert from SAMRecord to SAMRecordExt

Unsurprisingly, this doesn't work either (runtime error):

SAMRecordExt recext= (SAMRecordExt) sam.iterator().next();
>>> Exception in thread "main" java.lang.ClassCastException: htsjdk.samtools.SAMRecord cannot be cast to markDupsByStartEnd.SAMRecordExt
at markDupsByStartEnd.Main.main(Main.java:96)

How can I make the extended class work where the base class worked?

EDIT: More detail about the classes I'm using. sam object comes from

SamReaderFactory sf = SamReaderFactory.makeDefault();
SamReader sam= sf.open(new File(insam));

Full documentation is https://samtools.github.io/htsjdk/javadoc/htsjdk/index.html

like image 780
dariober Avatar asked Oct 20 '22 13:10

dariober


1 Answers

The Problem is:

sam.iterator().next()

returns a SAMRecord object

Which means

SAMRecordExt recext= sam.iterator().next();

will not work because a super class can not assigned to a sub class variable.

The general problem is that the subclass is more specific than the super class thats why you can't assign a super class object to a subClass variable because the super class doen't know the things which the sub class needs to know.

On the other hand the subclass knows the details of the super class and some more details which means you are able to assign a sub class object to a super class variable.

Solution for the Problem: (EDIT)

Normally you extend the class and are able to override the iterator method and return a well constructed iterator of the type you wish.

But the Problem I see here is that the factory creates your obj of type SamReader which you use to iterate over the SamRecords

SO -> you must extends the factory to return other type of SamReader and iterate later over your wished record types see the

Source code of the Factory class:

https://github.com/samtools/htsjdk/blob/master/src/java/htsjdk/samtools/SamReaderFactory.java

like image 60
Zelldon Avatar answered Oct 22 '22 04:10

Zelldon