简体   繁体   中英

Is it possible to extend a class that has an instance of itself as a field such that the subclass has an instance of the subclass instead?

I know that you could break down implementations of LinkedList into two categories. In one, the actuall LinkedList is a reference to the first of some linked Nodes, like this

public class LinkedList1<E>{

    class Node{
        E data;
        Node next;
    }

    Node head;

}

That version is probably better, but alternatively, there's a more 'direct' version, that makes things like deleting the head (head meaning the first element from the client's perspective) a bit trickier but still possible from within the instance of LinkedList2:

public class LinkedList2<E>{

    E data;
    LinkedList2 next;

}

I'm curious if there's any way to create LinkedList2Child extends LinkedList2 such that the next field is of type LinkedList2Child , perhaps involving reflection?

EDIT: this isn't preventing me from accomplishing anything since version 1 is available--I'm just curious about the problem in general, and this is an example.

I know that you can 'hide' fields in subclasses by declaring a field with the same name as the parent's field, but this won't work if you want to use parent methods that operate on that field.

Generics:

public class LinkedList2<E, T extends LinkedList2>{

    E data;
    T next;

}

public class LinkedSubclass extends LinkedList2<LinkedSubclass> {

}

It's subject to the usual restrictions on what you can do with generics (eg constructing new "next" values in the base class would require taking in the child type's class, or a factory), but would cover what you want.

This is called co-variance (or co-variant return types):

public static abstract class A
{
    public A get() { ... }
}

public static abstract class B extends A
{
    @Override
    public B get() { ... }
}

Method B#get() overrides A#get() . This is orthogonal (ie is conceptually unrelated) to generics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM