Call parent constructor in java

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.

Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow