java - Use extended class in place of base class -
java 1.6. have extended class include methods. use extended class in place of base class. however, classes use base class cannot "recognize" extended class. (recommended) fix?
i know has been asked many times in different flavors, can't it!
example- extend class samrecord
, use samrecordext
afterwords:
public class samrecordext extends samrecord{ public samrecordext(samfileheader header) { super(header); } }
now, while works:
samrecord rec= sam.iterator().next();
this gives me compilation error
samrecordext recext= sam.iterator().next(); >>> type mismatch: cannot convert samrecord samrecordext
unsurprisingly, doesn't work either (runtime error):
samrecordext recext= (samrecordext) sam.iterator().next(); >>> exception in thread "main" java.lang.classcastexception: htsjdk.samtools.samrecord cannot cast markdupsbystartend.samrecordext @ markdupsbystartend.main.main(main.java:96)
how can make extended class work base class worked?
edit: more detail classes i'm using. sam
object comes from
samreaderfactory sf = samreaderfactory.makedefault(); samreader sam= sf.open(new file(insam));
full documentation https://samtools.github.io/htsjdk/javadoc/htsjdk/index.html
the problem is:
sam.iterator().next()
returns samrecord
object
which means
samrecordext recext= sam.iterator().next();
will not work because super class can not assigned sub class variable.
the general problem subclass more specific super class thats why can't assign super class object subclass variable because super class doen't know things sub class needs know.
on other hand subclass knows details of super class , more details means able assign sub class object super class variable.
solution problem: (edit)
normally extend class , able override iterator method , return constructed iterator of type wish.
but problem see here factory creates obj of type samreader use iterate on samrecords
so -> must extends factory return other type of samreader , iterate later on wished record types see
source code of factory class:
https://github.com/samtools/htsjdk/blob/master/src/java/htsjdk/samtools/samreaderfactory.java
Comments
Post a Comment