Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces and instantiation

Tags:

java

I have been reading a book on Java (Sams Teach Yourself Java in 21 Days 6th edition) and I have a question.

Book says,

Interfaces cannot be instantiated: new can only create an instance of a non-abstract class.

Then it goes on and says a paragraph or so later that You can declare a variable to be of an interface type for eg.

Iterator loop = new Iterator();

Isn't that instantiating the interface as we are using new?

like image 360
Simon Avatar asked Jan 12 '23 10:01

Simon


1 Answers

The second declaration is wrong:

Then it goes on and says a paragraph or so later that "You can declare a variable to be of an interface type for eg. Iterator loop = new Iterator();"

You indeed can declare variable Iterator loop;, you can initialize it using method that returns Iterator, constructor of class that implements Iterator or using anonymous inner class, however you cannot instatiate Iterator directly.

EDIT:

I found this book online. But the 5th adition. Here are the quotes:

Remember that almost everywhere that you can use a class, you can use an interface instead. For example, you can declare a variable to be of an interface type: Iterator loop = new Iterator() When a variable is declared to be of an interface type, it simply means that the object is expected to have implemented that interface. In this case, because Iterator contains an object of the type Iterator, the assumption is that you can call all three of the inter- face’s methods on that object: hasNext(), next(), and remove().

Fantastic! The book that has 6th edition contains so stupid mistake! Unbelievable...

like image 57
AlexR Avatar answered Jan 25 '23 04:01

AlexR