gpt4 book ai didi

java - java中调用父构造函数

转载 作者:行者123 更新时间:2023-12-02 10:51:05 25 4
gpt4 key购买 nike

我有两个类 ParentChild,而 Parent 有一个需要 3 个参数的构造函数:

class Parent{
public Parent(String host,String path,int port){
}
}

现在我希望 Child 构造函数只需要一个参数,然后我尝试执行以下操作:

class Child extend Parent{
public Child(String url){
String host=getHostFromUrl(url);
String path=....
String port=...
super(host,path,port);
}
}

但这不起作用。

有解决办法吗?

顺便说一句,我无法访问 Parent 类。

最佳答案

super 的调用必须是构造函数主体中的第一条语句。来自 section 8.8.7 of the JLS :

The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).

您只需要内联调用:

public Child(String url) {
super(getHostFromUrl(url), getPathFromUrl(url), getPortFromUrl(url));
}

或者,解析一次为 URL 的更清晰的表示形式,并调用同一类中的另一个构造函数:

public Child(String url) {
this(new URL(url));
}

// Or public, of course
private Child(URL url) {
super(url.getHost(), url.getPath(), url.getPort());
}

(我还没有检查这些成员是否适用于 java.net.URL - 这更多的是一种方法而不是细节。根据您的实际要求进行调整。)

关于java - java中调用父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23333623/

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