0

I have a Java class which implements an interface, this class have a constructor that takes a String value and all the methods is that class are rely on that value in order to get work, so, what can i do if i want to deal with the interface directly and access the methods from it and as you know the interfaces can't have constructors so i can't assign that string value from it.

The Class:

public class XmlSource implements XmlInterface{

    XmlConf xconf = new XmlConf();
    URLProcess urlp = new URLProcess();
    private URL url;
    private String surl;

    public XmlSource(String surl) throws MalformedURLException {

        this.surl = surl;
        result = urlp.validate(surl);
        if(result == true){
            configure();
        }

    }

    public boolean configure() throws MalformedURLException {

            url = new URL(surl);
            xconf.setUrl(url);
            xconf.setParameters(urlp.parameters);
            xconf.setUrlPath(urlp.path);
            xconf.setHostName(urlp.hostName);
            return result;

    }

    public Document load() throws IOException, ParserConfigurationException,
            SAXException {

        // encoding the URL
        InputStream is = url.openStream();

        // loading the XML
        domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        builder = domFactory.newDocumentBuilder();
        doc = builder.parse(is);

        return doc;

        }
}

The Interface:

public interface XmlInterface {

    public boolean configure() throws Exception;
    public Document load() throws Exception;
}
Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118
  • In order to deal with the methods in the interface, create an instance of a class that implements the interface and call the methods on the class, in your case as @TheNewIdiot said use `new XmlSource(url)` – Sajan Chandran May 29 '13 at 11:01
  • It is unnecessary to make the methods in your interface public. They are always public by default. `boolean configure() throws Exception;` is enough... – Daniel Lerps May 29 '13 at 11:02

1 Answers1

1

You can assign a XmlSource object to XmlInterface type reference variable and then use that reference variable to call methods.

XmlInterface obj = new XmlSource(surl);
try
{
    boolean configure = obj.configure();
    Document document = obj.load();
}
catch(Exception e){
 // perform exception handling
}
AllTooSir
  • 48,828
  • 16
  • 130
  • 164