Call parent constructor in java

Deadly 提交于 2019-12-11 02:05:09

问题


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){
    }
}

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);
    }
}

But this does not work.

Any idea to fix it?

BTW, I have no access to Parent class.


回答1:


The call to super must be the first statement in the constructor body. From 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).

You just need to inline the calls:

public Child(String url) {
    super(getHostFromUrl(url), getPathFromUrl(url), getPortFromUrl(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());
}

(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.)




回答2:


Try something like

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

class Child extends Parent {
  public Child(String url) {
    super(getHost(url), getPath(url), getPort(url));
  }

  static String getHost(String url) {
    // Logic to calculate host
    return url;
  }

  static String getPath(String url) {
    // Logic to calculate path
    return url;
  }

  static int getPort(String url) {
    // Logic to calculate port
    return 8080;
  }
}


来源:https://stackoverflow.com/questions/23333623/call-parent-constructor-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!