-4

Java 8 introduced "default method" which allows describing the method's body.

I want to create one Interface and two child classes. In the Interface URL I'd like to have getURL() method:

public interface URL {
    int getURL() {
        return this.myURL;
    } // obviously
}

and in two child classes I'd like to define the myURL field:

public class MyURL1 implements URL {
     private String myURL = "http://test1.com";
}

public class MyURL2 implements URL {
     private String myURL = "http://test2.com";
}

which will be returned by getURL.

Is it possible in Java?

Павел Иванов
  • 1,863
  • 5
  • 28
  • 51

2 Answers2

3

No, this is not possible in Java.

The next similiar thing would be an abstract class:

abstract class UrlHolder {
    private String url;
    protected UrlHolder(String u) { url = u; }
    public String getUrl() { return url; }
}

and then

class UrlHolder1 extends UrlHolder {
    public UrlHolder1() {
        super("myurl1");
    }
}
class UrlHolder2 extends UrlHolder {
    public UrlHolder2() {
        super("myurl2");
    }
}
daniu
  • 14,137
  • 4
  • 32
  • 53
  • But won't it turn out the way that the next super overwrites the previous url value? – Павел Иванов Oct 02 '17 at 07:46
  • @paus `UrlHolder1` and `UrlHolder2` are separate classes, they won't get in the way of each other. Each instance will have an `url` field of their own, and all `UrlHolder1` `url`s will be set to "myurl1". Note that since it's private, it will never get changed over the lifecycle of an object. – daniu Oct 02 '17 at 07:53
  • yes, UrlHolder1 and UrlHolder2 are separate, but parent abstract class with url field is common. This is what confuses me. – Павел Иванов Oct 02 '17 at 08:51
1

The way you want it:

public interface URL {
    int getURL() {
        return this.myURL;
    } // obviously
}

Assumes you have a state, which is not allowed in interfaces, therefore I think you need to consider using abstract classes instead, e.g.:

public abstract class URL {

    private String myUrl;

    public URL(String url) {
       this.myUrl = url;
    }

    public String getURL() {
        return this.myURL;
    } // obviously
}

And then

public class MyURL1 implements URL {
      public MyURL1() {
         super("http://test1.com");
      }
}
Artem Barger
  • 40,769
  • 9
  • 59
  • 81