在Java中调用父构造函数 [英] Call parent constructor in java
问题描述
我有两个班级 Parent
和 Child
,而 Parent
有一个需要3个参数的构造函数:
I have two class Parent
and Child
, while the Parent
have a constructor which needs 3 arguments:
class Parent{
public Parent(String host,String path,int port){
}
}
现在我要 Child
构造函数仅需要一个参数,然后我尝试执行以下操作:
And now I want the Child
constructor need only one argument, then I try to do something like this:
class Child extend Parent{
public Child(String url){
String host=getHostFromUrl(url);
String path=....
String port=...
super(host,path,port);
}
}
但这不起作用。
有什么想法要解决吗?
顺便说一句,我无权访问父母
类。
BTW, I have no access to Parent
class.
推荐答案
对 super
的调用是构造函数主体中的第一条语句。摘自第8.8.7节JLS :
The call to super
must be the first statement in the constructor body. From section 8.8.7 of the JLS:
构造函数主体的第一个语句可能是对相同类或直接超类(第8.8.7节)。
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,并在同一类中调用另一个构造函数:
Alternatively, parse once to some cleaner representation of the URL, and call another constructor in the same class:
public Child(String url) {
this(new URL(url));
}
// Or public, of course
private Child(URL url) {
super(url.getHost(), url.getPath(), url.getPort());
}
(我尚未检查这些成员是否会为<$ c $工作c> java.net.URL -这更多的是方法而不是细节。请根据您的实际要求进行调整。)
(I haven't checked whether those members would work for java.net.URL
- this is more by way of an approach than the details. Adjust according to your actual requirements.)
这篇关于在Java中调用父构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!