gpt4 book ai didi

Java:在最终类中实现接口(interface)的类

转载 作者:行者123 更新时间:2023-11-30 06:06:16 24 4
gpt4 key购买 nike

这可能是一个愚蠢的问题,但我在这里感到困惑。我有以下情况:

Main.java

public class Main {

public static void main (String args[]){
GenericTag[] arr = new GenericTag[2];
arr[0] = new Authentication("", "", "", "");
arr[1] = new Document("", "", "", "");
byte[] foo= Base64.decodeBase64(XmlBuilder.generate(arr));
System.out.println(new String(foo));
}

XmlBuilder.java

public final class XmlBuilder {
private static final String OPEN_TAG = "";
private static final String CLOSE_TAG = "";

public static byte[] generate(GenericTag[] tags){

String xml = OPEN_TAG;
for(int i=0; i<tags.length; i++){
xml += tags[i].xml;
}
xml += CLOSE_TAG;

return Base64.encodeBase64(xml.getBytes());
}

public interface GenericTag{
public String getXml();
}

public class Authentication implements GenericTag{
private static final String OPEN_TAG = "<authentication>";
private static final String CLOSE_TAG = "</autentication>";
//some tags

public Authentication (/*some parameters*/){
xml = OPEN_TAG;
//xml building
xml += CLOSE_TAG;
}

@Override
public String getXml() {
return xml;
}
}

public class Document implements GenericTag{
private static final String OPEN_TAG = "<document>";
private static final String CLOSE_TAG = "</document>";
//some tags

public String xml;

public Documento (/*some params*/){
xml = OPEN_TAG;
//xml building
xml += CLOSE_TAG;
}
@Override
public String getXml() {
return xml;
}
}
}

我无法让它工作。编译器表示 Authentication 和 Document 无法解析为类型。如果我明确声明 new XmlBuilder.Authentication 它会说

No enclosing instance of type XmlBuilder is accessible. Must qualify the allocation with an enclosing instance of type XmlBuilder (e.g. x.new A() where x is an instance of XmlBuilder).

我在这里做错了什么?

最佳答案

创建类AuthenticationDocumentpublic static。由于这些不是静态,因此您只能从 XmlBuilder 实例实例化它们。

Java inner class and static nested class - 您可以在这里找到更多信息

关于Java:在最终类中实现接口(interface)的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44584174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com