简体   繁体   English

Java中的通用抽象类

[英]Generic abstract classes in Java

I'm trying to make a simple little class where I can make something similar to a macro in C/C++. 我正在尝试制作一个简单的小类,在其中我可以制作类似于C / C ++中的宏的内容。 Basically I want to be able to call the following code when I need to perform a few actions though a list of objects, like so: 基本上,当我需要通过对象列表执行一些操作时,我希望能够调用以下代码:

new IteratableList{
   void action() {
       // do something
   }
}.perform();

I haven't programmed in Java in quite a while, and I can't figure out what is wrong with my code when I try to add the abstract action method: 我已经有一段时间没有使用Java编程了,在尝试添加抽象操作方法时,我无法弄清楚代码出了什么问题:

import java.util.List;
import java.util.Iterator;

public abstract class IteratableList<T> {
    public void perfrom(List<T> ls) {
        Iterator<T> l = ls.iterator();
        while (l.hasNext())
            action(l.next());
    }

    private abstract void action(<T> obj);
}

My code doesn't get any errors until I type that last method. 在我键入最后一个方法之前,我的代码不会收到任何错误。 I get errors telling me to remove abstract from the method header, and when I change that I get a list of other errors. 我收到错误消息,告诉我从方法标头中删除摘要,并且在更改时得到了其他错误列表。 I feel like I missed a fundamental thing here. 我觉得我错过了这里的基本内容。 Does any one see a glaring error? 有人看到明显的错误吗?

private abstract void action(<T> obj);

should be 应该

protected abstract void action(T obj);

When you have a generic method you have to define it in the method signature as such: 如果有通用方法,则必须在方法签名中按如下方式定义它:

protected abstract <T> void action(T obj);

unless (and this is the case here) the generic parameter is defined at class level. 除非 (这里就是这种情况), 否则泛型参数是在类级别定义的。

You should also remove the private modifier and make it protected instead. 您还应该删除private修饰符并使其protected abstract indicates the method has to be overridden, but private indicates subclasses can't access it. abstract表示必须重写该方法,而private表示子类无法访问它。 protected expands the accessibility of private to subclasses. protected扩展了private对子类的可访问性。

Instead of 代替

private abstract void action(<T> obj);

I think you want 我想你要

protected abstract void action(T obj);

The syntax for the generic was wrong, and you can't have a private abstract method. 泛型的语法有误,您不能使用私有的抽象方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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