I am curious as to how Java knows which implementation of an interface will be used when a method is called.
So below are snippets of the code where I have trouble understanding how it "magically" works:
The Interface "LotListener":
public interface LotListener { public void bidUpdate( Lot lot, Bid bid); } The Implementations of "LotListener" are BidStatistics and Person.
Now here is the code I had before changing all the BidStatistics and Person to the interface:
public class Lot { private HashSet<**Person**> bidders; private **BidStatistics** bidStats; public Lot(int number, String description, **BidStatistics** bidStats) { bidders = new HashSet<**Person**>(); this.bidStats = bidStats; } public boolean bidFor(Bid bid) { **Person** nextBidder; bidders.add( bid.getBidder() ); Iterator iterateBids = bidders.iterator(); if(highestBid == null) { // There is no previous bid. highestBid = bid; bidStats.bidUpdate( this, bid ); return true; } else if(bid.getValue() > highestBid.getValue()) { // The bid is better than the previous one. highestBid = bid; while ( iterateBids.hasNext() ) { nextBidder = (LotListener) iterateBids.next(); nextBidder.bidUpdate( this, bid ); } bidStats.bidUpdate( this, bid ); return true; } else { // The bid is not better. return false; } } Now when I change all the Person and BidStatistics to the interface LogListener:
public class Lot { private HashSet<**LotListener**> bidders; private **LotListener** bidStats; public Lot(int number, String description, **LotListener** bidStats) { bidders = new HashSet<**LotListener**>(); this.bidStats = bidStats; } public boolean bidFor(Bid bid) { **LotListener** nextBidder; bidders.add( bid.getBidder() ); Iterator iterateBids = bidders.iterator(); if(highestBid == null) { // There is no previous bid. highestBid = bid; bidStats.**bidUpdate**( this, bid ); return true; } else if(bid.getValue() > highestBid.getValue()) { // The bid is better than the previous one. highestBid = bid; while ( iterateBids.hasNext() ) { nextBidder = (LotListener) iterateBids.next(); nextBidder.**bidUpdate**( this, bid ); } bidStats.**bidUpdate**( this, bid ); return true; } This code still works. My questions is why?
How does it know when to use the implementation of bidUpdate from Person, and when to use the implementation of bidUpdate from BidStatistics??
EDIT: Really sorry about the ** around some of the code. I tried to bold them to highlight it but I guess that doesn't work.