The KnightOfTheRoundTable class that owns the HolyGrailQuest Class :
My main concerns in the KnightOfTheRoundTable Class :
Can we instantiate an interface? I can't understand this "instantiation" even if Quest was implemented directly by KnightOfTheRoundTable. But what I have here is Quest that's implemented by a subclass. That's just beyond comprehension.
Another wonder of the world. How can an interface be a container of an instance of a class?
Well, those type of statements are allowed in Java. The first line
is a declaration, whereas
An interface is nothing but an 100% abstract class. During the declaration part, you are declaring an object that may contain any class that implements the interface. We used to tell that the classes or interface that have inheritance as their relationship, is having a "IS-A" relationship. For example, if I have a class named Bird, and if i inherit this class in "Pigeon" class, then we tell that "Pigeon is-a bird".
This will be useful in accessing a common method, that are present in all the subclasses. Again for example, if i have one more class in the above example, say, "Parrot", and if i want to call the fly() [assume we have it] method in both the classes, it is efficient to use a Bird class object [even if it is an interface], and store an instance of Parrot or Pigeon. At runtime, the JVM decides the object to invoke the method.
Not exactly. That code assigns (not initializes) several objects to that Bird variable named "obj" (not Bird object), one after the other. So after line 6, that variable contains a reference to a Falcon object. So when you call the "fly" method of that variable, the "fly" method of the Falcon object to which it refers is called.
Those other four objects which were created, and now have nothing referring to them? No, they aren't "removed". They just sit there in memory until the garbage collector runs and notices they have nothing referring to them. This may happen at some time in the future but nothing is guaranteed except that the garbage collector will remove them from memory before the program runs out of memory.
A magnificient life is loaded with tough challenges. En garde tiny ad: