Instanciate generic subclass of an abstract class

Hello,
I'm writing a litle file manager API for my application, organised like a Database: a table filled by records.
I want my table to be able to be able to manage different types of records (but one record type by table!), so I have this hierarchy:
the abstract record class:
public abstract class Record {
     public Record() {
     public abstract void readFrom(DataInput in, int length) throws IOException;
     public abstract void writeTo(DataOutput out) throws IOException;
     public abstract int prepareToWrite();
}the abstract atomic record class, extending the abstract record class:
public abstract class AtomicRecord<T> extends Record {
     public AtomicRecord() {
     public AtomicRecord(T value) {
          super();
     public abstract T getValue();
     public abstract void setValue(T value);     
}and, for example, the StringRecord class:
public class StringRecord extends AtomicRecord<String> {
     code doesn't matter.
}now, I want to make a table of generic records:
public class RandomRecordAccessAppendableFileTable<RecordType extends Record>{
     public final RecordType getRecord(long id) throws IOException {
          RecordType record = new RecordType();
}problem: the RecordType is obviously not instanciable, as it extends Record, and not StringRecord. But I still want to instanciate a new StringRecord from a RandomRecordAccessAppendableFileTable<StringRecord> and a FooRecord from a RandomRecordAccessAppendableFileTable<FooRecord>.
Is there a way I can do this?
Thank you in advance.

This is just my opinion, so you might ignore it: The design you are targeting is a result of misunderstanding what Generics are for and what Generics may provide in their current state. Their only purpose is to provide compile-time type safety. Creating instances the way you want to do seems more runtime focused, i.e., when generic information is gone.
Maybe, you should consider passing a factory at construction time that enables to create a record of a specific type. Using the class object requires reflection, which will introduce implicit contracts to record classes and potential runtime failures.

Similar Messages

  • Geting subclass info from abstract class

    Does ne one know how i can retreive informtion from the subclasses of an abstract class by creatinig an instance of the abstract class.
    are Methods such as getClass used?

    Does ne one know how i can retreive informtion from
    the subclasses of an abstract class by creatinig an
    instance of the abstract class.You can never create an instance of the abstract class. That is why they are called abstract.
    >
    are Methods such as getClass used?
    Coming to your actual question, a superclass will not know anything about its children. So you will have to do something else get that information.
    Maybe inspecting all the classes in a classloader and checking its parent will be an option. I do not think this is possible, because ClassLoader does not provide a mechanism to get all the classes.
    Somebody else might give you a better answer. I am just trying to answer one part of your question concerning abstract classes.

  • Abstract class methods

    I'm confused. Is this true or false.
    The great thing about polymorphism is that you can call one method. If the subclass inherited that method, it will be customized and perform a different duty. That way, the action it performs will depend on 1>whether or not it's a sub or super class and also 2>if the method was overridden if it was a subclass.
    Now, my confusion. If an object reference is to a Super-abstract-class... how do the method calls and properties go?? well let me let you answer for me. Thanks so much in advance for this clarification.

    Yes. You are - pretty much.
    The abstract class, as such, can never be instantiated. BUT a class derived from the superclass IS an instance of the superclass.
    Silly example:
    abstract public class Animal {
       public Animal() {
       public abstract int getNumberOfLegs();
    }That's our animal class, and we know that anything that's an animal has a number of legs - but we can't just create a "generic" animal.
    public class Cat extends Animal {
       public Cat() {
          super();
       public int getNumberOfLegs() {
          return legCount;
       public void maim(int legsToRemove) {
          legCount -= legsToRemove;
          if(legCount < 0 ) legCount = 0;
       private int legCount = 4;
    }A Cat is a specific type of animal, so we can find out how many legs it has (usually 4). Note again that a cat IS an animal, so Cat IS an instance of Animal.
    Java even provides a special operator to test this:
    Cat cat = new Cat();
    System.out.println("A cat is a cat: " + (cat instanceof Cat));
    System.out.println("A cat is an animal: " + (cat instanceof Animal));The term used to describe the "Guarantee" that a subclass of an abstract class (or an implementation of an interface) is usually and technically a "contract", but I prefer to think of it as a "Promise" since you can break the promise by messing with the bytecode - at which point the JVM will spot the lie and complain !
    D.

  • Abstract class causes JNI GetByteArrayElements to crash

    I'm having a problem with a subclass of an abstract class that is accessing a JNI function. I'm using Java 1.4.2.
    I started out with a single class that reads data from a serial port (via a JNI call) and then parses the data. When I test this class, the read/parse works correctly.
    Since I have to create multiple parsing protocols, I decided to create an abstract class that contained the reading functionality and a subclass that parses the data. When I did this, the 1st call to GetByteArrayElement never returns (nor do I get a stack dump trace).
    I also tried making the super-class non-abstract and over-writing the prase method(s). I got a similar failure.
    I can't imagine what the issue might be - why would splitting the original object into two (superclass/subclass) cause such a problem?
    I've include relevent snippits of code.
    Thanks for the help!
    ===== JNI Code =====
    extern JNIEXPORT jint JNICALL Java_vp_jni_Serial_read (JNIEnv *env,
         jclass class, jint fd, jbyteArray buf, jint cnt, jint offset)
         jboolean     iscopy = JNI_FALSE;
         // FAILS ON CALL; NEVER RETURNS!!!!
         const jbyte *data = GetByteArrayElements (env, buf, &iscopy);
         const uchar     *b;
         int               num,
                        rc;
         b = (uchar *) &data[offset];
         num = cnt;
         do
              rc = read (fd, (char *) b, num);
              if (handleReadException (env, rc) != 0)
                   (*env)->ReleaseByteArrayElements (env, buf, (jbyte *) data, 0);
                   return rc;
              num -= rc;
              b += rc;
         } while (num > 0);
         (*env)->ReleaseByteArrayElements (env, buf, (jbyte *) data, 0);
         return cnt;
    }==== Java Native Calls ====
    public class Serial
         public int read (byte[] data, int length, int offset)
              throws IOException
              return read (fd, data, length, offset);
         private static native int read (int fd, byte[] buf, int cnt, int offset)
              throws IOException;
    }==== Abstract super-class ====
    package vp.parse;
    import java.io.IOException;
    import java.io.InterruptedIOException;
    import java.io.SyncFailedException;
    import vp.jni.Serial;
    import vp.jni.Exec;
    import vp.data.ControlData;
    public abstract class Parse extends Thread
         protected static final int     ERROR = -1;
         private static final int     LOC_TIMEOUT = 3000;
         private Serial          link;
         private int               port;
         private boolean          running = false;
         private int               baud = Serial.B9600;
         protected abstract void reset ();
         protected abstract void parse ();
         public Parse (int port, String id, int baud)
              this.port = port;
              this.baud = baud;
              start ();
              synchronized (this)
                   try
                        wait (5000);
                   } catch (Exception e)
                        System.out.println (id + " Thread failed to synchronize");
              System.out.println ("Done");
         public void run ()
              link = new Serial(port);
              try
                   link.open();
                   link.setBaud (baud);
                   link.setTimeout (LOC_TIMEOUT);
              catch (Exception e )
                   link = null;
                   return;
              running = true;
              synchronized (this)
                   notify ();
              while (running)
                   parse ();
         protected int read (byte[] buf, int packetSize, int offset)
              if (offset >= packetSize)
                   offset = 0;
              if (offset > 0)
                   for (int i=0; i<packetSize - offset; i++)
                        buf[i] = buf[offset+i];
                   offset = packetSize - offset;
              try
                   int cnt = link.read (buf, packetSize - offset, offset);
                   offset = 0;          // all data is good
              // ready to 'close down' executable
              catch (Exception exp)
                   running = false;
                   return ERROR;
              return offset;
    }==== Sub-class to handle parsing ====
    package vp.parse;
    public class Eis extends Parse
         private static final int     PACKET_SIZE = 3 + 69 + 1;     // hdr, data, csum
         private byte[]          buffer = new byte[PACKET_SIZE];
         private int               offset = 0;
         public Eis (int port)
              super (port, "GR EIS", Serial.B9600);
         protected void reset ()
              offset = 0;
         protected void parse ()
              do
                   offset = read (buffer, PACKET_SIZE, offset);
                   if (offset == ERROR)
                        offset = 0;
                        return;
                   // parse code here
              } while (parse failed);
         public static void main (String[] argv)
              Eis e = new Eis (3);
              try { Thread.sleep (10000); } catch (Exception x) {}
    }

    The issue was the following:
    I had declared a buffer in the sub-class;
    private byte[] buffer = new byte[PACKET_SIZE];
    And the assumption would be that by the time it got used, it would be initialized. But that's not the case. Why?
    The sub-class called the super class constructor. At this point in time, buffer[] is not valid.
    The super class constructor spawns the child thread and waits for the spawned thread to finish initialization.
    The spawned thread creates the serial port, informs the constructor it's 'done' and starts to parse incoming data.
    The parse() code is the sub-class passes the uninitialized buffer to the JNI code and GetByteArrayElements crashes because id doesn't like a null pointer.
    Since the parent thread doesn't regain control to finish the construction, buffer[] never gets initialized.
    So much for synchronized thread spawning in a constructor...

  • Why a nested class can instantiate an abstract class?

    Hi people!
    I'm studying for a SCJP 6, and i encountered this question that i can figure it out but i don't find any official information of my guess.
    I have the following code:
    public class W7TESTOQ2 {
        public static void main(String[] args) {
           // dodo dodo1 = new dodo();
            dodo dodo2 =new dodo(){public String get(){return "filan";}};
            dodo.brain b = dodo2.new brain(){public String get(){return "stored ";}};
            System.out.print(dodo2.get()+" ");
            System.out.println(b.get());
    abstract class dodo
        public String get()
            return "poll";
        abstract class brain
            public abstract String get();
    }I know that abstract classes cannot be instantiated but i see that in this example, with a nested anonymous class it does (dodo and brain classes). My guess is that declaring the nested class it makes a subclass of the abstract class and doing so it can be instantiated. But i can't find any documentation about this.
    Does anybody know?
    Really thanks in advance.
    Regards,
    Christian Vielma

    cvielma wrote:
    Another question about this. Why can't i declare a constructor in the nested class? (it gives me return type required)You cannot declare a constructor, because in one line you're declaring a new class (the anonymous inner class) as well as constructing an instance of it.
    What you can do, however, is if the abstract class (or the superclass, in any case, it doesn't need to be abstract) defines several constructors, you can call them.
    public abstract MyClass {
        public MyClass() {
            // Default do nothing constructor
        public MyClass(String s) {
            // Another constructor
    // Elsewhere
    MyClass myclass = new MyClass("Calling the string constructor") {
    };But you can't define your own constructors in the anonymous inner class.
    Also, since the class is anonymous, what would you name the constructor? :)
    Edited by: Kayaman on 26.6.2010 22:37

  • Doubt on abstract classes

    Hi,
    I have doubt in abstract classes,please clarify my doubt.....my doubt is
    I have one abstract class,in that i have three methods...
    Now I have created one subclass for that abstract class....
    I defined all those methods that are there in abstract class in the sub class......and I wrote some other methods in that sub class....
    Now my question is ----->can I make the methods that are declared in abstract class invisible to the people who are using the sub class???
    Please tell me the answer...
    Thanks in advance,
    sirisha.

    ya I got it....
    Please see the code and tell me wether it is correct or not...
    abstract class One
    int i=10;
    private void display()
    System.out.println("One:display");
    public void show()
    System.out.println("One:show");
    public abstract int intadd(int j);
    class Two extends One
    int i=100;
    public void display()
    super.display();
    System.out.println("TestThr:display");
    public void show()
    //super.show();
    System.out.println("TestThr:show");
    public int intadd(int j)
    if (j==1)
         return i;
         else
    return super.i;
    public class TestThr
    public static void main(String args[])
    Two t=new Two();
         t.display();
         t.show();
         System.out.println(t.intadd(1));
    }

  • Abstract Class Misunderstanding

    I have a GUI Main class that has action listeners that need to call sub classes passing in data entered by the interacting user. The subclass being called from the GUI is an Abstract class. Since abstract classes can't be instantiated, how do I pass down the data entered by the user? If this does not make sense, please reply so and I'll post code as an example.
    Thanks in advance.

    You pass an instance of a subclass of the abstract class, one that is not itself abstract.

  • Object of an abstract class

    Can we create object of an abstract class ?

    As Richard Brünning mentioned in his reply, we can't instantiate the object with reference to the Abstract Class. i.e.
    DATA: O_OBJ TYPE REF TO ZCL_ABS_CLASS.
    CREATE O_OBJ.   " << This will give syntax error
    But you can surely use the abstract class to reference the object. At run time, based on your required you can instantiate the object with actual reference type to the subclass of the abstract class. Like:
    DATA: O_OBJ TYPE REF TO ZCL_ABS_CLASS.
    * ZCL_ABS_CLASS_SUB is sub class of the ZCL_ABS_CLASS
    CREATE O_OBJ TYPE ZCL_ABS_CLASS_SUB.
    Regards,
    Naimesh Patel

  • Why are we using Abstract class?

    Why are we using Abstract class? What is specify use of Abstract class?

    The way I understand it....and I may be wrong because
    I am very new....is that by making the class abstract
    you will add abstract methods to it. Those abstract
    methods MUST be defined in in any subclass that
    inherits from the abstract class thereby making the
    abstract a template for subclasses.
    If your animal class is abstract then you would need
    an abstract method (Which is just siganture, no body)
    of say "numberOfLegs". Then in your dog and cat
    classes which extend animal you must define a
    "numberOfLegs" method with appropriate code.it isn't mandatory for an abstract class to have abstract methods. if a class does have abstract methods, the class must be abstract. but the following is perfectly legal
    public abstract class NoAbstractMethods {
      public void doStuff() {
         // do stuff
    }a subclass of an abstract class can also be abstract, and as such need not implement any additional methods

  • Problems with extension of generic abstract class

    Hello,
    I'm having some problems with the extension of a generic abstract class. The compiler tells me I have not implemented an abstract method but I think I have. I have defined the following interface/class hierarchy:
    public interface Mutator<T extends Individual<S>, S> {
         public void apply( T<S> ind );
    public abstract class AbstractMutator<T extends Individual<S>, S> implements Mutator<T, S> {
         public abstract void apply( T<S> ind );
    }Now I implement AbstractMutator as such:
    public class BinaryMutator extends AbstractMutator<StringIndividual<Integer>, Integer> {
         public void apply( StringIndividual<Integer> ind ) { ... }
    }The compiler says:
    BinaryMutator.java:3: ga.BinaryMutator is not abstract and does not override abstract method apply(ga.Individual<java.lang.Integer>) in ga.AbstractMutator
    Why does it say the signature of the abstract method is apply(Individual<Integer>) if I have typed the superclass as StringIndividual<Integer>?
    Thanks.

    Yes, but the abstract method takes an arg of type <T extends Individual>. So it takes an Individual or a subclass thereof, depending on how I parameterise the class, right? StringIndividual is a subclass of Individual. So if I specify T to be StringIndividual, doesn't the method then take an arg of type StringIndividual?

  • Abstract class - subclass

    a quik question: if I have a abstract class define a method, and a subclass implementing it, and a third class with an instance casted as the abstract class, would the following method in the subclass then return the instance casted as subclass? :
    public Subclass getInstance() {
    return this;
    Stig.

    oops.... cant return SubClass....

  • Generics/Abstract class question

    I'm not sure exactly what my problem is here. I am creating an abstract class for a number of other data types that I am creating. The purpose of this class is to track changes so that the GUI can prompt the user to save changes if they try to exit without saving. I want to do this by storing a reference of the original object and then making changes on a new object. I am running into problems though. Right now I am trying to define the clone method in that class and am getting an error.
    public abstract class ChangeableDataType<T extends ChangeableDataType>{
        protected T old;
        public Object clone(){
            T t = new T(); // Error occurs here
            //Stuff
        }The error I get is unexpected type on the line where I try to call a new T(). Is this not something that I can do? I have tried to put any code in that I thought might have the problem.

    No, that isn't something you can do. I'm sure it's discussed in more (and better) detail in [the Generics FAQ|http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html] though.

  • Generics w/ abstract classes and contructors

    Here's my setup:
    abstract class AC
    AC(){};
    AC(String S){};
    abstract boolean IsValid();
    class RC extends AC
    public RC(){.........................};
    public RC(String S){...........................};
    public boolean IsValid(){...........................};
    class ACContainer<T extends AC>
    public void ErrorFunc(String Str)
    T tobj = new T(Str);
    My problem is that it doesn't let ErrorFunc create a "new T(Str)" when I create an ACContainer<RC> RCContObj with a call to ErrorFunc.
    Why not?
    I get "unexpected type"
    Edited by: mikeatrxs on Apr 24, 2008 1:10 PM
    Edited by: mikeatrxs on Apr 24, 2008 1:11 PM

    Reac a Generics tutorial. Type parameters are erased at compile time. There is no way it knows at runtime what class you want to create an instance of, unless you additionally pass in a Class object that tells it what class it is. It makes more sense if you ask, what happens when you "erase" the generic type parameters? Any valid Generics program should be able to erase to a valid non-Generics program and vice versa. But how are you going to erase the "new T(Str)"? How would you do this without Generics?

  • Invoking method of final subclass of abstract class is slow

    hi,
    I've diagnosed a performance regression in my code which boils down to the example at the end of the post.
    Would it be possible to have the vm dynamically figure out that within the hotspot in the test method, its
    safe to ditch the dynamic dispatch and skip that overhead?
    I thought marking the method as final would allow the vm to peform some run-time optimisations - I'm pretty sure I've been able to measure that in different situations; marking the test method's parameter (a) as final, also doesn't help.
    Rather than have an abstract class, its looking like the performance requirements will dictate some copy and paste to
    help the vm along - does anyone know if I'm missing something here?
    thanks in advance,
    asjf
    The output I see (using 6.0 update 10) is:
    B foo 28
    B bar 95
    C foo 29
    C bar 86
    D foo 26
    D bar 92
    E foo 29
    E bar 82
    public class MethodCallPerfTest {
         public static void main(String[] args) {
              test(new B());
              test(new C());
              test(new D());
              test(new E());
         public static void test(A a) {
                   long start= System.currentTimeMillis();
                   for(int i=0; i<8000000; i++)
                        a.foo();
                   System.out.println(a.getClass().getSimpleName()+" foo "+(System.currentTimeMillis() - start));
                   long start= System.currentTimeMillis();
                   for(int i=0; i<8000000; i++)
                        a.bar();
                   System.out.println(a.getClass().getSimpleName()+" bar "+(System.currentTimeMillis() - start));
    abstract class A {
         int j;
         final void foo() {j++;}
         abstract void bar();
    final class B extends A {
         int k;
         void bar() {k++;}
    final class C extends A {
         int l;
         final void bar() {l++;}
    class D extends A {
         int m;
         final void bar() {m++;}
    class E extends A {
         int n;
         void bar() {n++;}
    }

    is it because references to the final fields are resolved at compile-time ?
    such that the compiler must know the value of USE in:if(USE){
      // a
    // b at compile time so it can remove either "b" or "a". I think so. hmm.

  • Abstract method called in an abstract class

    Hello,
    I am writing some code that I'd like to be as generic as possible.
    I created an abstract class called Chromozome. This abstract class has a protected abstract method called initialize().
    I also created an abstract class called Algorithm which contains a protected ArrayList<Chromozome>.
    I would like to create a non abstract method (called initializePopulation()) which would create instances of Chromozome, call their method initialize() and full the ArrayList with them.
    In a practical matter, only subclass of Algorithm will be used, using an ArrayList of a subclass of Chromozome implementing their own version of initialize.
    I have been thinking of that and concluded it was impossible to do. But I'd like to ask more talented peaple before forgetting it !
    Thanks,
    Vincent

    Ok, let's it is not impossible, juste that I had no idea of how doing it :-)
    The difficulty is that Algorithm will never have to deal with Chromozome itself, but always with subclass of Chromozome. This is usually not an issue, but in that case, Algorithm is required to create instances of the desired subclass of Chromozome, but without knowing in advance wich subclass will be used (I hope what I say makes any sense).
    Actually I may have found a way in the meantime, but maybe not the best one.
    I created in Algorithm an abstract method :
    protected abstract Chromozome createChromozome()The method initializePopulation will call createChromozome instead of calling directly the constructor and the initialize() method of Chromozome.
    Then subclass of Algorithm will implement the method createChromozome using the desired subclass of Chromozome.

Maybe you are looking for

  • Transfer data from a table to another table

    Hello I want to transfer data from a table in one server to another table in a different server, I want to do this on a nightly job, what will be the best way, please advise, thank you.

  • Mac Pro 5,1 (mid 2012) compatible graphic cards

    Hello everyone. Which graphic cards are compatible with the Mac Pro 5,1 (mid 2012)? It came with an ATI Radeon HD 5770 1024MB but the card presented problem and now need replacing. Its a very hard-to-find model in my city, so might I have other possi

  • Text element in Sapscript

    Hi friends, When I do client copy, text elements are not getting transferred. Can anyone help me ???

  • Why is tethering to Linux no longer working?

    After a while of using windows and osx I now need to tether from iphone 4s to Linux (Fedora) PC. I know it used to work with same pc software around ios version 6. For some reason it no logner works with ios 7.0.4. After plugging the iphone in using

  • How can I specify simple math like in a Formula Node but on the front panel?

    If the Formula node had a "text" property, that would work for me, because I could limit my inputs and outputs to N floating-point numbers. LabVIEW once had such a thing but it was in an add-on math library, and I don't remember what it was called. S