Inheriting from a Generic type

Hello all,
I'm doing some tests on compiling generics and get confused about the case where a class not considered as a generic could inherit from a generic type. Shouldn't it be implicitly considered as a generic ?
To illustrate my problem, consider the following:
I declare a class MyCollection as following:
public class MyCollection extends Vector {...}
vector is a Generic type as it is declared as public Vector<E> {...}
But if I try to instantiate MyCollection, I'm not allowed to do it as:
MyCollection<Object> col = new MyCollection<Object>();
but I'm allowed to do:
MyCollection col = new MyCollection();
So what happens to the E generic variable of Vector ?
I can't clearly explain what is MyCollection. I should have implicitly considered it as a Generic type.
Can someone explain ?

Not really. I've probably not been clear.
Java5 exposes in its apis a class defined as:
public class Vector<E> ...
Now I define my own colletion class defined as:
public class MyCollection extends Vector { ...
This syntax is allowed by the compiler. Note that I
didn't define my class MyCollection as a Generic.
BUT, as the superclass IS a generic, How is
interpreted MyCollection ?
As a kind of Vector<Object> ?
What about the E generic type defined in Vector, the
superclass ?
I Thought, this way of feining my class MyCollection
implied it to be Generic also, i.e. that this kind of
definition means implcitly that it is equivalent as
defining:
public class MyCollection<E> extends Vector<E> ...
But that's not clear to me !!!
What about you all ???Your definition:
public class MyCollection extends Vector
does not make MyCollection generic implicitly, or at all. It is equivalent to
public class MyCollection extends Vector<Object>
which is basically the same as using a pre-1.5 Vector. The superclass may be defined as a generic type but that doesn't matter here. MyCollection is not generic, period. It can be interpreted "as a kind of Vector<Object>".
The superclass doesn't matter to whether or not your class is generic. Your class is generic if and only if you declare it as a generic
The only way to make your class a proper generic extension of Vector is:
public class MyCollection<E> extends Vector<E>.
Is there any reason you don't want to do this?

Similar Messages

  • Tutorial for make a non-generic type class from a generic type interface

    Hi there,
    How can I make a non-generic type class from a generic type interface?
    I appreciate if somebody let me know which site can help me.
    Regards
    Maurice

    I have a generic interface with this signature
    public interface IELO<K extends IMetadataKey>
    and I have implemented a class from it
    public class CmsELOImpl<K extends IMetadataKey> implements IELO<K>, Cloneable, Serializable
    then I have to pass class of an instance CmsELOImpl to AbstractJcrDAO class constructor whit below signature
    public abstract class AbstractJcrDAO<T> implements JcrDAO<T> {
    public AbstractJcrDAO( Class<T> entityClass, Session session, Jcrom jcrom ) {
              this(entityClass, session, jcrom, new String[0]);
    So I have made another class extended from AbstractJcrDAO. Below shows the code of this class and itd constructor
    public class ELODaoImpl extends AbstractJcrDAO<CmsELOImpl<IMetadataKey>> {
         public ELODaoImpl( Session session, Jcrom jcrom ) {
         super(CmsELOImpl.class , session , jcrom, MIXIN_TYPES);
    and as you see in its constructor I am calling the AbstractJcrDAO constructor by supper method
    then I got this error on the line of super method
    The constructor AbstractJcrDAO(class<CmsELOImpl>, session, Jcrom, String[]) is undefined.
    as I know java generics are implemented using type erasure. This generics are only
    in the java source file and not in the class files. The generics are only used by the compiler and
    they are erased from the class files. This is done to make generics compatible with (old) non generics java code.
    As a result the class object of AbstractJcrDAO<CmsELOImpl<IMetadataKey>>
    is AbstractJcrDAO.class. The <CmsELOImpl<IMetadataKey>> information is
    not available in the class file. As far as I understand it, I am looking a way
    to pass <CmsELOImpl<IMetadataKey>>, if it is possible at all.
    Maurice

  • VS2013.4 Class Diagram inheriting from a base type (how do I)

    Hi Folks,
    I am creating a VS2013.4 class diagram and one of my classes inherits from a base class System.Configuration.ProviderBase.
    In VS2010 there is a way to do this and the class new class would show (Abstract Class -> ProviderBase) in its description.   Is there a way to
    When I look at the properties for the class there is no property specifying inheritance.  In VS2010 there is an 'Inherits' property.
    Regards
    Andy

    If the User-Agent contains "Fennec/" then it is Firefox for mobile. If it contains "Android" then it is running on an Android device.
    We have an open request to add more device info to the User-Agent header. For details, see:
    https://bugzilla.mozilla.org/show_bug.cgi?id=625238
    We'll consider this request, but we must balance it against user privacy, and attacks like browser fingerprinting. For now, in cases where you don't detect a known device from the User-Agent header, you can ask the user instead (for example, have them choose from a list of devices). This will also benefit Android users who have changed their browsers' User-Agent headers for various reasons.

  • Hide a field inherited by the content type in a custom list definition

    The requirement is to create new content type that inherits from a Parent content type. I also created custom document library definition that uses the newly created content type.
    There are some fields that are inherited from the parent type that I would like "NOT TO" show in the edit/display form in the libraries created based on the new list definition.
    How can I achieve this? In the list definition, I added ShowInEditForm="FALSE" and ShowInDisplayForm="FALSE" ShowInViewForm="FALSE".
    But these fields won't hide and it still shows up when a new document is uploaded. Any help would be appreciated.
    Thanks!

    Hey,
    Have
    this link for your reference. It will help you.
    Thanks. Please mark it as an answer if it helps.

  • Import from database an internal table with generic Type : Web Dynpro ABAP

    Hi everyone,
    i have a requirement in which i'm asked to transfer data flow between two frameworks, from WD Component to another. The problem is that i have to transfer internal tables with generic types. i used the import/ export from database approache but in that way i get an error message saying "Object references and data references not yet supported".
    Here is my code to extract a generic internal table from memory.
        DATA l_table_f4 TYPE TABLE OF REF TO data.
      FIELD-SYMBOLS: <l_table_f4> TYPE STANDARD TABLE.
      DATA lo_componentcontroller TYPE REF TO ig_componentcontroller .
      DATA: ls_indx TYPE indx.
      lo_componentcontroller =   wd_this->get_componentcontroller_ctr( ).
      lo_componentcontroller->fire_vh_search_action_evt( ).
      ASSIGN l_table_f4 TO <l_table_f4>.
    *-- Import table for Help F4
      IMPORT l_table_f4 TO <l_table_f4> FROM DATABASE indx(v1) TO ls_indx ID 'table_help_f4_ID'.
    The error message is desplayed when last instruction is executed " IMPORT l_table_f4...".
    I saw another post facing the same problem but never solved "Generic Type for import Database".
    Please can anyone help ?
    Thanks & Kind regards.

    hi KIan,
    go:
    general type
    TYPE : BEGIN OF ty_itab,
               field1 TYPE ztab-field1,
               field2 TYPE ztab-field2,
    *your own fields here:
               field TYPE i,
               field(30) TYPE c,
               END OF ty_itab.
    work area
    DATA : gw_itab TYPE ty_itab.
    internal table
    DATA : gt_itab TYPE TABLE OF ty_itab.
    hope this helps
    ec

  • How to create an array with Generic type?

    Hi,
    I need to create a typed array T[] from an object array Object[]. This is due to legacy code integration with older collections.
    The method signature is simple:public static <T> T[] toTypedArray(Object[] objects)I tried using multiple implementations and go over them in the debugger. None of them create a typed collection as far as I can tell. The type is always Object[].
    A simple implementation is just to cast the array and return, however this is not so safe.
    What is interesting is that if I create ArrayList<String>, the debugger shows the type of the array in the list as String[].
    If I create ArrayList<T>, the class contains Object[] and not T[].
    I also triedT[] array = (T[]) Array.newInstance(T[].class.getComponentType(), objects.length);And a few other combinations. All work at runtime, create multiple compilation warnings, and none actually creates T[] array at runtime.
    Maybe I am missing something, but Array.newInstace(...) is supposed to create a typed array, and I cannot see any clean way to pass Class<T> into it.T[].class.getComponentType()Returns something based on object and not on T, and T.class is not possible.
    So is there anything really wrong here, or should I simply cast the array and live with the warnings?
    Any help appreciated!

    Ok. May be you could keep information about generic type in the your class:
    public class Util {
        public static <T> T[] toTypedArray(Class<T> cls, Object[] objects){
            int size = objects.length;
            T[] t = (T[]) java.lang.reflect.Array.newInstance(cls, size);
            System.arraycopy(objects, 0, t, 0, size);
            return t;
    public class Sample<T> {
        Class<T> cls;
        T[] array;
        public Sample(Class<T> cls) {
            this.cls = cls;
        public void setArray(Object[] objects){
            array = Util.toTypedArray(cls, objects);
        public T[] getArray(){
            return array;
        public static void main(String[] args) {
            Object[] objects = new Object[] { new LinkedList(), new ArrayList()};
            Sample<List> myClass = new  Sample<List>(List.class);
            myClass.setArray(objects);
            for(List elem: myClass.getArray()){
                System.out.println(elem.getClass().getName());
    }

  • Earmarked funds during goods receipt (GR) is not inherited from PO.

    Hi, Everybody u2026
    We are using Earmarked Funds relevant for FM updating, but, during goods receipt (GR) and invoice receipt (IR) it is not inherited from purchase order (PO).
    In ME21N the account assignment is F and the system ask us to enter the GL Account, Order and additional the Earmarked Funds. The system is deriving correctly the fund, the funds center and the commitment item from those entered in the Earmarked Funds.
    However, during goods receipt and invoice receipt, the Earmarked Funds is not inherited from purchase order (PO) besides the others account assignments (order, fund, funds center and commitment item ) in the coding block.
    Best regards,
    Thanks

    Hello,
    I will provide some hints:
    - If it is a service PO, please check the Note 972276 (Service Purchase orders only).
    - If the posting is related to Asset, please kindly check:
        a. Note 684659
        b. Check if you have a derivation rule in FMDERIVE with the function module FMDT_READ_MD_ASSET.
        c. Check in your FI-AA customizing if you have activated the account
          assignment element but you have not specified an account assignment type for
          account assignment object for APC balance sheet postings (see note 684659 for
          details).
    I hope it helps
    Best Regards,
    Vanessa Barth.

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

  • Cost Center Inheritance from Org Unit

    Good day all,
    Can someone please advise regarding cost center inheritance from org units?
    I understand the inheritance concept, however simple need to know if the CCenter is added to the org unit via A011 relationship, does the system physically create a A011 relationship on the position inhertiting the cost center from the org or does the system simply pick up the realtionship from the org unit relationsip for use in IT0001 field KOSTL (cost center)?
    Thanks guys, have a lovely day!
    Christy

    Hi Christy,
    As we know cost centre(K) is an unusual object in OM.Two type of objects internal  whose master record are in database table beloging to sap erp hcm and eexternal object whose master data belong to other application areas.Cost centre is an external object that is used to represent origin of costs.Inheritance concept is on the basis of whoch cost centre are assigned in org plan.
    directly related cost centre is called master cost centre and they are made via A011 cost centre assignment relationsip.they can be made at org unit,position or work centre and nornmally its org unit that common.Org unit at the top are asisgned the cost centre as a best practise so that all the org units below or reporting will inherit the same.
    Similarly multiple cost centre assignments can also e made through 1018 infotype(cost centre distribution).Inheritance also applied to them aswell.
    Hope this helps.
    No Worries
    KG

  • Rules for casting generics type

    I know that there is a section in jsr14 spec about rules of casting generic types, but it seems outdated with
    JLS3.
    It is obvious that e.g. Class<String> cannot be casted to Class<Integer>.
    However in
    <T,V> void foo (Class<T> ct) {
    Class<V> cv = (Class<V>)ct;
    The cast is permitted by the compiler though of course marked as unchecked (The cast should be rejected according to jsr14 spec since none of the types is a subtype of the other).
    So the question is: what are the rules, compiler uses to check casts?

    1. There is an (unsafe) explicit cast from l1 to l2.
    2. There is an implicit cast in the last line, because
    l2 is a List<String>, the line is compiled to the
    equivalent of
    System.out.println(" result:" + (String) l2.get(0));
    // ClassCastException: java.lang.String

  • What is wrong by inheriting from Object?

    Hi and thank you for reading my question,
    I have tried the following program:
    import java.util.*;
    interface I {}
    class A1 {}
    class B1 extends A1  implements I {
        B1() {}
    class B2 extends A1 implements I {
        B2() {}
    class Cell<V> 
    V  value;
    <T extends V> Cell(T a) {value = a;}
    V get() { return value; }
    class Foo {
        void  test(boolean b){
         Cell<? extends B1> cb1 = new Cell<B1>(new B1());
         Cell<? extends B2> cb2 = new Cell<B2>(new B2());
         Cell<? extends I> c1 = ( b ? cb1 : cb2);
         Cell<? extends A1> c2 = ( b ? cb1 : cb2);
    }and I have got the following error:
    Test.java:31: incompatible types
    found   : Cell<capture of ? extends java.lang.Object&I&A1>
    required: Cell<? extends A1>
         Cell<? extends A1> c2 = ( b ? cb1 : cb2);
                                     ^
    1 errorWhy c2 is incorrect and c1 is correct?
    It seems that there is a bug by inheriting from Object.
    I have tried the same code but now class A extends
    a class different than Object:
    import java.util.*;
    interface I {}
    class A1 extends Vector<Integer>{}
    class B1 extends A1  implements I {
        B1() {}
    class B2 extends A1 implements I {
        B2() {}
    class Cell<V> 
    V  value;
    <T extends V> Cell(T a) {value = a;}
    V get() { return value; }
    class Foo {
        void  test(boolean b){
         Cell<? extends B1> cb1 = new Cell<B1>(new B1());
         Cell<? extends B2> cb2 = new Cell<B2>(new B2());
         Cell<? extends I> c1 = ( b ? cb1 : cb2);
         Cell<? extends A1> c2 = ( b ? cb1 : cb2);
    }This program compiles without any error. Both c1 and c2 are correct.

    A bug, I've submitted bug 6278798.

  • Instantiation of generic type

    Hi.
    I have an issue with instantiating of generic type. My issue is similar to this Re: creating instance of generic type post.
    So I have the following class
    public class VehicleForm<V extends Vehicle>{
    private V vehicle;
    private Double price;
    private Class<V>vItemClass;
    public V getVehicle(){
    return this.vehicle;
    public void setVehicle(V vehicle){
    this.vehicle=vehicle;
    public Double getPrice(){
    return this.price;
    public void setPrice(Double price){
    this.price=price;
    private final Class<V> getGenericClassInstance() {
    Class<V> persistentClass = null;
    Type genericType = getClass().getGenericSuperclass();
    if (genericType instanceof ParameterizedType) {
    ParameterizedType pType = ((ParameterizedType) genericType);
    // obtaining first generic type class
    persistentClass = (Class<V>) pType.getActualTypeArguments()[0];
    return persistentClass;
    public VehicleForm(){
    this.vItemClass=getGenericClassInstance();//vItemClass is null
    this.vehicle=this.vItemClass.newInstance();//null poiner exception
    I cannot write in default constructor
    public VehicleForm(){
    this.vehicle=new V();//runtime error will occure
    because of generic type
    For obtaining generics we can use java reflection functionality. Generic type list in runtime is obtaining through ParameterizedType. The code in getGenericClassInstance is standard to instantiate generic type var.
    But unfortunately in my case it doesn't work. getGenericClassInstance returns null. Line Type genericType = getClass().getGenericSuperclass(); doesnt get generic type which is instance of ParameterizedType, so the condition if (genericType instanceof ParameterizedType) is false. My genericType is Object instance, but not ParameterizedType. So I cannot create Class<V> instance from null.
    Can anybody help me? Thanks in advance.
    Edited by: 877736 on 06.08.2011 12:50
    Edited by: 877736 on 06.08.2011 12:51

    877736 wrote:
    My issue is similar to this Re: creating instance of generic type post...Did you look at the answers given there? Pretty much the same as ttjacobs is telling you here: This is NOT what generics was created for.
    Even if you can do it, the code is likely to be messy, complex and brittle.
    Also: this thread is in the wrong category, as the other poster (you?) was already told. There is a "Generics" section under Java APIs.
    My suggestion: rethink your solution.
    Winston

  • Retrieving generic type and letter

    Hi,
    I have a generic class -
    public class AAA <T extends BBB>implements Serializable From which I want to get its generic type (the easy part),
    and the generic type letter representation (In this case - T).
    Can I do this by reflection? If so how,
    Otherwise - is there any way I can do that which doesn't involve parsing the class as text?
    Thanks,
    Sharon.

    Class.getGenericDeclaration() should lead you to the letter T.
    The actual runtime type cannot be obtained because of erasure.
    If the class is under your control, you can play a trick:
    add to the constructor(s) a Class parameter and pass the actual type
    used.

  • [ANN] Java IDE with generic type support

    Hello all!
    We are proud to announce that we have just released version 5.0 of our Java IDE CodeGuide.
    CodeGuide 5.0 offers full support for generic types as defined in JSR 14. Features are:
    - Fast incremental on-the-fly compilation
    - On-the-fly error checking of the whole project
    - Code completion
    - Usage search
    - Refactoring (like Renaming, Class moving, etc.)
    - and more...
    A 30-day trial can be downloaded from our web page at
    http://www.omnicore.com
    Any feedback regarding JSR 14 support is much appreciated.
    Best regards,
    Dennis Strein
    Omnicore Software

    I wrote a class MultiMap<K, V> extends Map<K, Set<V>>
        // Various constructors, methods, fields.
        public Set<V> get(K key)
            // Implementation
    } It compiles fine with the Sun reference compiler, but a friend tells me that CodeGuide 5.0 build 504 complains "There already is another method with the same erasure." It could be that CodeGuide is correct and Sun wrong, because I can see that there might be issues with overriding the get(Object) method with a get(K), but I thought I'd mention it.

  • Getting generic type at runtime

    Example:
    public class GenericTest {
    private List<String> list = new List<String>();
    How can I get the type String at runtime?
    Class c = GenericTest.class;
    Field[] fiels = c.getFields();
    for (Field f: fields) {
    Class fc = f.getDeclaringClass();
    // What are the next steps to to get String.class from fc?
    }

    Generic types (ie. the ones inside the < >) get Erased at compile-time. All this type information is therefore not available at run-time
    Google "Java Generics Erasure" to get some more info. (There's a Generics forum by the way!)

Maybe you are looking for