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.

Similar Messages

  • No instances can be created from abstract classes

    Dear SAPGurus,
    I have developed a oData Service in my backend system & able to register the service in the gateway hub system. When i try to execute the metadata of the service from gateway system i am able to see the metadata with list of entity types availble in the data model.
    But when i try to execute with entity set i am getting the following error.
    "The class 'ZCL_ZGRC_DATA_MODEL_DPC' is abstract. No instances can be created from abstract classes."
    Where my data model provider class name is  'ZCL_ZGRC_DATA_MODEL_DPC'
    Kindly help me.
    Thanks & Regards,
    Rumeshbabu S

    Hello Rumesh,
    I do not think the error which u are getting is because of System Alias setting in SPRO.
    Its something else which is really strange.
    However the below is the setting to be maintained in GW SPRO system alias when u have a environment setup like u have now.
    I mean the way u have created service and registered -
    In ECC system u have created service using builder.
    In GW system u have registered it and trying to access now via an RFC destination.
    We have the same setup like u have now and we do not have any issues. We have also maintained the System Alias like i have shared in screen shot.
    Check your System Alias config once in SPRO. But i dont think this is causing problem in your case. Still check once.
    As per my understanding, from GW its trying to hit the DPC class and hence i feel system alias setting is correct in your case.
    Problem is something else which is really strange.
    Check error logs and see if it can. Share the error log please.
    Regards,
    Ashwin

  • How to get info from a .class file at run time? thanks for help

    I need to get methods and properties (variables) from a .class file at run time.
    as u know, javap.exe can do that in an independent way. but i need to get info at run time once the .class or packeges have been changed, javap is not suitable in the case.
    i try to read data directly from .class file but it's hard to know the file format.
    e.g. a class looks like (java file):
    class MyClass extends Frame
    int i0;
    String s0;
    public String getName()
    if the file is compiled to .class file, how to get properties (variables: i0,s0) and methods String getName() from the .class file by an applicaton at run time?
    Doclet is not suitable for speed reason, it is too slow to get right info in right format.
    Thanks for any help, please write a little bit more in detail if you know.

    Use the Java Reflection API. Have a look at the Reflection section of the Java Tutorial located at http://java.sun.com/docs/books/tutorial/reflect/index.html

  • 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.

  • From abstract class to public class

    I am developing a editor base application...wondering that how to cancel the abstract class and put all the abstract class methods into the public class..?? thanks

    Is this a C++ question? If so, you should post it in the C++ forum. If it is a Java question, post in the Java forum.
    In either case, please make your question more specific. It sounds like all you have to do is copy the functions from the abstract class to the derived class, remove the dependency on the abstract class, and delete the abstract class from the source code. Presumably that is not what you are asking.

  • How to read data from abstract class

    Hi,
    I have an abstract class which has a try block in the run method which looks like this:
    public void run()
    throws exception
    try
    ArrayList xCoord = new ArrayList();
    Double xValue = null;
    for (j=0; j<10; j++)
    xValue = new Double (table.getX(j).toDouble());
    xCoord.add(xValue); // to populate arraylist
    i also have the required catch statements, i have not written them here to keep in concise.
    My question is: How do I read the values stored in the xCoord arraylist from another 'concrete' class derived from the above abstract class.
    I know that for this, I first have to be able to execute the above "run" method, because that is how the arraylist will get populated with values. But how do I do this from the concrete class?
    Then, once the arraylist is formed, how do I read the values from the concrete class, without copying all the code?
    Any guidance will be really helpful. Thanks -- Vinay.

    Add a public or protected accessor (getter) method to retrieve the value calculated in run(). Modify run() to store the results in an instance variable in the abstract class.
    - Saish

  • Method inheritence from abstract classes, and arguments

    I'm trying to do something a little weird. I'm writing a pretty complicated wrapper/adapter for two platforms, and I'd like to have an abstract method passed on to child classes, but with the type of the single argument specified by the child class. Is this possible?
    Example
    public abstract class AbstractParent {
    public abstract void foo([ambiguousType] arg);
    public class ChildOne extends AbstractParent {
    public void foo(TypeA arg) {
    //body
    public class ChildTwo extends AbstractParent {
    public void foo(TypeB arg) {
    //body
    }TypeA and TypeB have no common supertype beyond Object, and I'd rather not just do instanceof checks and throw errors. Does anyone know of a solution? Can I elaborate any better?

    Perhaps you could use generics?
        public abstract class AbstractParent<E> {
            public abstract void foo(E arg);
        public abstract class ChildOne extends AbstractParent<String> {
            public void foo(String arg) {
        public abstract class ChildTwo extends AbstractParent<Integer> {
            public void foo(Integer arg) {
        }

  • Why does this abstract class and method work without implement it?

    hi,
    I have seen many times that in some examples that there are objects made from abstract classes directly. However, in all books, manual and tutorials that I've read explain that we MUST implement those methods in a subclass.
    An example of what I'm saying is the example code here . In a few words that example makes Channels (java.nio.channel) and does operations with them. My problem is in the class to make this channels, because they used the ServerSockeChannel class and socket() method directly despite they are abstracts.
       // Create a new channel: if port == 0, FileChannel on /dev/tty, else
       // a SocketChannel from the first accept on the given port number
    private static ByteChannel newChannel (int netPort)
          throws Exception
          if (netPort == 0) {
             FileInputStream fis = new FileInputStream ("/dev/tty");
             return (fis.getChannel());
          } else {
    //CONFLICT LINES
             ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
             ssc.socket().bind (new InetSocketAddress (netPort)); //<--but here, this method (socket) is abstract. WHY RETURN A SOCKET????????  this mehod should be empty by default.
             System.out.print ("Waiting for connection on port "
                + netPort + "...");
             System.out.flush();
             ByteChannel channel = ssc.accept();
             ssc.close();
             System.out.println ("Got it");
             return (channel);
       } I test this code and works fine. So why can it be??
    Also, I read that the abstract classes can't have static methods. Is it true???
    Please Help!!
    PS: i have seen this kind of code many times. So i feel that I don't understand how its really the abstract methods are made.
    PS2: I understand that obviously you don't do something like this: *"obj = new AbstractClass(); "*. I dont understand how it could be: ServerSocketChannel ssc = ServerSocketChannel.open(); and the compiler didn't warn.

    molavec wrote:
    ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
    The static method creates an instance of a class which extends ServerSocketChannel, but is actually another non-abstract class.I thought that, but reading the documentation I saw that about open() method:
    Opens a server-socket channel.
    The new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.
    The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.
    ...and the problem is the same openServerSocketChannel is abstract, so i don't understand how it could return a ServerSocketChannel.There is a concrete implementation class that has implemented that method.
    I guess that really the open() method use a SelectorProvider's subclase but it doesn't appear in the doc.It doesn't need to. First, you don't care about those implementation details, and second, you know that if the class is abstract, it must use some concrete subclass.
    Ok, I speak Spanish by default (<-- this sounds like "I am a machine", ^_^' ). So, I didn't know how to say that the method would be {}. Is there a way to say that?? I recommendable for me to know, for the future questions o answers.Not sure what you're saying here. But the other respondent was trying to explain to you the difference between an abstract method and an empty method.
    // abstract method
    public abstract void foo();
    // empty method
    public void bar() {
    Which class does extend ServerSocketChannel? I can not see it.It may be a package-private class or a private nested class. There's no need to document that specific implementation, since you never need to use it directly.

  • 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...

  • About Abstract class

    Hi All,
    I m inherting from abstract class . So is it mandatory for me to provide implemenation for all methods that r defined in abstract class
    i m getting error like this:
    subclass class is not abstract ,does not override abstract method "methodname" in superclass
    Thanks in advance
    Waiting for replies
    Amar

    - you need to override all methods from your abstract
    superclass.....You don't have to override anything unless you want to, but you have to supply implementation for all abstract classes. If you don't you will have to declare the subclass abstract and let another subclass down the hierarchy finish the job. Eventually all abstract classes must be implemented otherwise objects cannot be instantiated. For that a class must be fully concrete.

  • 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.

  • 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

  • Abstract Class and polymorphism - class diagram

    Hi,
    ]Im trying to draw a class diagram for my overall system but im not too sure how to deal with classes derived from abstract classes. I'll explain my problem using the classic shape inheritance senario...
    myClass has a member of type Shape, but when the program is running shape gets instantiated to a circle, square or triangle for example -
    Shape s = new circle();
    since they are shapes. But at no stage is the class Shape instantiated.
    I then call things like s.Area();
    On my class diagram should there be any lines going from myClass directly to circle or triangle, or should a line just be joining myClass to Shape class?
    BTW - is s.Area() polymorphism?
    Thanks,
    Conor.

    Sorry, my drawing did not display very well.
    If you have MyClass, and it has a class variable of type Shape, and the class is responsible for creating MyClass, use Composition on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it has a class variable of type Shape, and the class is created elsewhere, use Aggregation on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it is used in method signatures, but it is not a class variable, use Depedency on your UML diagram to link Shape and MyClass. The arrow will point to Shape.
    Shape and instances of Circle, Triangle, Square, etc. will be linked using a Generalization on your UML diagram. The arrow will always point to Shape.
    Anything that is abstract (class, method, variable, etc.) should be italicized. Concrete items (same list) should be formatted normally.
    BTW, the distinction between Composition, Aggregation and Dependency will vary from project to project or class to class. It's a gray area. Just be consistent or follow whatever guidelines have been established.
    - Saish

  • 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

Maybe you are looking for