-2

I am confused on one scenario of interface.Below is the code in which I haven't declare the toString() method in interface.
It is the method of object class.But still toString() method is able to execute from the parent class reference variable .But the rule says that before calling the child class method it first look method in interface, if method is present then call the child class method but in this scenario How toString() is executed without declaration in interface
please explain me

    public interface Parent {
    void show();
}

class Base implements Parent {
    public void show() {
        System.out.println("hey it is going to be execute");
    }

    public String toString() {
        return "itspossible";
    }

    public static void main(String[] args) {
        Parent parent = new Base();
        System.out.println(parent.toString());
    }
}
Freak
  • 6,786
  • 5
  • 36
  • 54
henrycharles
  • 1,019
  • 6
  • 28
  • 66

7 Answers7

5

This works because every class extends the Object class implicitly. Therefore any implementation of any interface, has the toString() method available.

Peter Jaloveczki
  • 2,039
  • 1
  • 19
  • 35
1

Its because the toString method is included on Object which every class is derived from. The method is being called from the Object class.

I found this question answered by Jon Skeet that explains it well:

Does an interface by default extend Object?

Community
  • 1
  • 1
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

In the end, parent is an object reference from Base class. Note that all classes extends from Object class, thus having the methods defined in Object class such as toString.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

it is because Object class is a base class for every class and it includes toString method. So when you call toString with parent's reference, it'll call parent's toString().

voidMainReturn
  • 3,339
  • 6
  • 38
  • 66
0

The variable parent is just a reference which is referring to its subtype Child. Here you are creating an object of Child which by default extends Object class. You are overriding the toString method hence giving this output.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
0

You are not calling toString method of interface but it's Bash Class method. Each object have a default implementation of toString method even you not explicit implement it.

How can instance of interface access method of Object class?

Community
  • 1
  • 1
bNd
  • 7,512
  • 7
  • 39
  • 72
0

You may want to have a look at the following discussion. The Java language works as if there was a super interface that all interfaces, including the one above in your comment, and the Object class inherit from, which declares all the methods that the Object class implements. Unfortunately, that interface doesn't really exist, the compiler just behaves as if it would exist.

blackpanther
  • 10,998
  • 11
  • 48
  • 78