Reputation: 19938
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
?
Upvotes: 4
Views: 203
Reputation: 466
If there are two classes: "Circle" and "Rectangle" which implement the interface "Area" and define their own version of implemented methods getParams() and calculateArea(),
public static void main(String[] args) {
Area area; //no direct instatiation
Rectangle rect = new Rectangle();
Circle circ = new Circle();
area = rect;//assign as another object; indirect instantiation
area.getParams();
area.calculateArea();
area = circ;
area.getParams();
area.calculateArea();
}
This code will work fine. Notice that the interface object area is created but not instantiated directly. It is later assigned as the object of the class which implemented it.
Upvotes: 0
Reputation: 115328
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...
Upvotes: 5
Reputation: 21831
You cannot create instance of interface. What this book is referring to, is probably an anonymous inner class that implements given interface. For example, you can create a Runnable
, like this:
Runnable instance = new Runnable() {
@Override
public void run() {
...
}
};
In case of Iterator
interface, you'd have to implement all 3 methods defined there: next()
, hasNext()
and remove()
.
Upvotes: 4