Use extended class instead of base class

Java 1.6. I added a class to include some methods. Now I would like to use an extended class instead of a base class. However, classes that can use the base class cannot “recognize” the extended class. What is a (recommended) fix?

I know that it has been asked many times in different tastes, but I can’t get it!

Example. Extend the SAMRecord class and use the SAMRecordExt afterword:

 public class SAMRecordExt extends SAMRecord{ public SAMRecordExt(SAMFileHeader header) { super(header); } } 

Now that 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 

No wonder 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 : In more detail about the classes that I use. sam object comes from

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

Full documentation https://samtools.imtqy.com/htsjdk/javadoc/htsjdk/index.html

+5
source share
1 answer

Problem:

 sam.iterator().next() 

returns a SAMRecord object

What does it mean

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

will not work because the superclass cannot be assigned to a subclass variable.

The common problem is that the subclass is more specific than the superclass, so you cannot assign a superclass object to the subClass variable because the superclass does not know what the subclass needs to know.

On the other hand, a subclass knows the details of a superclass and some other details, which means that you can assign a subclass object to a superclass variable.

Solution: (EDIT)

You usually extend the class and you can override the iterator method and return the well-constructed iterator of the type you want.

But the problem that I see here is that the factory creates your object of type SamReader, which you use to iterate through SamRecords

SO -> you have to expand the factory to return another SamReader type and repeat later on your desired record types, see

Source code of the factory class:

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

+3
source

All Articles