-1

I know that my question is dumb, but things are a little unclear in my head. I created an interface who has a default method, let's name it Dumb(). What I am trying to do is to use this.argument somewhere in this method, but that didn't work. I know that an Interface can't have instances, but that interface is implemented by a class, let's name it A. A has an instance in main method, named a, through I call my Dumb() method( a.Dumb()). My question is, why I can't have this if I call my method(who is inherited after all)? this isn't the reference of the object through I call the method? And I also know that an variable of the interface type can refer to any object of the classes that implements that interface.

I have a vague idea about the question, but a clear explanation will really help. Thanks in advance!

Cipri
  • 69
  • 1
  • 8
  • 1
    I don't understand what you're asking. Can you post some code? Such as what you tried to do in your interface and what happened when you tried it. – khelwood Jul 03 '19 at 22:04

1 Answers1

2

I interpret your situation like this:

interface Foo {
  default int Dumb() {
    return 2*this.argument;
  }
}

class A implements Foo {
  int argument = 42;

  public static void main(String[] args) {
    A a = new A();
    System.out.println(a.Dumb());
  }
}

and your question as

A has an argument field, so why do I get this error:

Foo.java:4: error: cannot find symbol
    return this.argument;
               ^
  symbol: variable argument
1 error

This is because Java requires interfaces to be valid by themselves. They can not reference undeclared fields, even if all currently implementing classes happen to have a field by the same name.

This is unlike JavaScript, where references are resolved at runtime, and unlike C++, where templates can be used to resolve references per use.

In Java, you would instead declare that that all instances of Foo must have a way to get the argument you're interested in by adding a (potentially non-default) method that implementing classes can provide:

interface Foo {
  default int Dumb() {
    return 2*getArgument();
  }
  int getArgument();
}

class A implements Foo {
  int argument = 42;

  public int getArgument() {
    return argument;
  }

  public static void main(String[] args) {
    A a = new A();
    System.out.println(a.Dumb());
  }
}
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • This does seem like the correct answer, though I was hoping Cipri would clarify the question further. – VGR Jul 03 '19 at 22:08
  • That's exactly what I was looking for. Thanks for the proper answer! Now everything is clear. – Cipri Jul 04 '19 at 06:05