简体   繁体   中英

I have one generic method in my abstract class. How do I make it work?

I have a class called Contact, which is the superclass of classes named PersonalContact and BusinessContact.

I have one abstract method in my class which is supposed to tell the subclasses to implement it. The method is

public abstract Set<T> getEventsWithinPeriod(DateTime start, DateTime end);

The T is there to be interchanged with the different type of events in each subclass. PersonalContacts have birthdays, and BusinessContacts have meetings. The problem is I am getting an error saying T cannot be resolved to a type , but isn't that the whole point of generics?

I tried putting the in the class header as well

public abstract class Contact<T> implements Comparable<Contact>{

but the compiler gives me a warning saying

Contact is a raw type. References to generic type Contact<T> should be parameterized.

How do I fix this?

It should introduce a formal type parameter:

public abstract <T> Set<T> getEventsWithinPeriod(Class<T> type, DateTime start, DateTime end);

It will actually work even without the parameter Class<T> type . But looks like you plan to instantiate that T inside the method (which you can't do because of type-erasure). So that paramter is there to help instantiate the actual-type reflectively at runtime.

Since you want to tie T with the subclass instead of getEventsWithinPeriod method, declare T as parameter for contact.

public abstract class Contact<T>
{
    public abstract Set<T> getEventsWithinPeriod();
}

class DOB
{
}
class BMeeting
{
}

class PersonalContact extends Contact<DOB>
{
    @Override
    public Set<DOB> getEventsWithinPeriod() 
    {
        // TODO Auto-generated method stub
        return null;
    }
}


class BusinessContact extends Contact<BMeeting>
{
    @Override
    public Set<BMeeting> getEventsWithinPeriod() 
    {
        return null;
    }
}

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