cast priorityQueue to my customized interface - java

public class testCast {
public interface dataQueue extends Queue<Object>{};
public static void main (String test[]){
dataQueue queue = (dataQueue) new java.util.PriorityQueue<Object>();
queue.add("Test");
System.out.println(queue.peek());
}
}
I am wondering why this would cause a casting error....
it would work if I do
Queue queue = (Queue) new java.util.PriorityQueue<Object>();
Does anyone know why??
Thanks in advance

Put simply, because a PriorityQueue is a Queue, but not a DataQueue. The actual class definition matters in Java: just because two interfaces are identical doesn't mean you can cast any implementation of one to the other.
DataQueue is an interface that extends the Queue interface.
PriorityQueue is a class that implements the Queue interface.
It does not implement the DataQueue interface.
Therefore, a PriorityQueue cannot be cast to DataQueue.
The hierarchy might make it clearer: just because they have a common ancestor doesn't mean you can cast one to the other.
Queue
________|________
| |
DataQueue PriorityQueue
To be even more pedantic about it, let's ramp up the clarity, since the relationship between Queue and DataQueue is different from the relationship between Queue and PriorityQueue. The following MSPaint diagram uses solid lines for inheritance, and dashed lines for interface-implementation.
So, you can't get from a PriorityQueue directly to a DataQueue. If you did really want to be able to make a PriorityQueue and call it a DataQueue for some reason, this is what you could do: extend PriorityQueue with a new class, and implement your DataQueue interface.
public class MyQueue extends PriorityQueue<Object> implements DataQueue {
// Anything you want goes here, or just leave it empty if you only want the default constructor.
}
Then you can write DataQueue q = new MyQueue(); to your heart's content.
Finally, note that this wouldn't work if you tried to inherit from two different classes. Java does not support multiple inheritance. This hierarchy is only possible because DataQueue is an interface, rather than a class.

Related

Defining priority queue

Consider the following declaration of the priority class class PriorityQueue<E extends Comparable<E>> extends Queue<E> { in contrast to the one provided in the Java packages, which has a comparator as an attribute to compare. This instead forces the object for which the priority queue is maintained to have its comparable implementation. Are there any pros and cons of this approach?
My Thoughts:
One thing I can think of is that this will force the priority queue to use the object comparators and won't provide the ability to implement its custom comparator as the user of the class may want to build the queue based on some different comparator.
Consider the following declaration of the priority class class PriorityQueue<E extends Comparable> extends Queue {}
What if you want to put an object in the queue, and this object does not implement the Comparable interface.
There is no need to restrict the placed object must implement the Comparable interface, which is more flexible.
For the same object, the logic of comparison may be inconsistent in different scenarios, so a comparator needs to be passed in from the outside, and the object itself does not need to implement a comparator.
(Above are my personal thoughts)

Abstract interface

I'm defining an interface to handle different kind of input sources like CSV files, SQL Tables and so on, so that I can easily copy data from one to the other.
In order to achive this I have an interface for a reader and one for a writer. Since they have some common attributes I wanted to define an abstract interface of ICommonContainer.
The common container interface is incomplete, because it only defines a subset, so I figured that, if I add abstract, it shouldn't be instantiatable when applied to a class, but it is.
So is there some way to declare an interface as incomplete similar to an abstract class?
So the interfaces looks like this:
public interface ICommonContainer
{
public void foo();
};
public interface Reader extends ICommonContainer
{
public data read();
};
public interface Writer extends ICommonContainer
{
public void write(data objects);
};
where reader and writer should be complete, but base is not.
There is no such thing as Abstract interface. We make a class abstract in order to make it non-instantiable. And any interface by nature is non-instantiable only.
As far as your issue is concerned, you can make your class implement any number of interfaces. In your case, since your interfaces are a part of same inheritance hierarchy, you don't need to implement both Base interface, and Reader or Writer interface. So, let it implement either Reader or Writer interface.
On the other hand, if you want to make a class which only implements ICommonContainer interface, non-instatible, just make that class abstract. That will be enough.
public abstract class SomeClass implements ICommonContainer {
// Either define the method in interface or leave it.
}
As in the above example, your SomeClass cannot be instantiated, as it is defined abstract.
The common container interface is incomplete, because it only defines
a subset, so I figured that, if I add abstract, it shouldn't be
instantiatable when applied to a class, but it is.
No, you can't instantiate the interface.
And no, there is no way of preventing some class to implement that interface.
It is your job to implement Reader and Writer (Your example names with applied Java naming conventions) and you don't have to implement Base.
No you can't declare an interface abstract.
And you cannot prevent the world to have a class which implements your inteface and isn't abstract (if it is public).
I think this is ok, if someone can write a complete class using just your ICommonContainer, there is no problem.
You could make the interface package private which might accomplish what you want, but the bigger question is why?
In the Java library there are many interfaces that are "incomplete"; or a better way to explain it is they are partially complete. List being one of them.
A List can be considered partially complete, because typically you need something more. Such as ordering (ArrayList), or assurance of fast inserts (LinkedList). The concrete classes take care of the completeness.
What you are trying to do goes against decent design principles. I consider this poor design principles because you should you design your Interfaces as being enough for some level. Given the list example, for some classes, knowing that there is an iteratable collection of objects is enough. Which makes for a good interface design. The user of the interface is loosely coupled from the implementation of such.
You can have a "partial" interface the has to do with reading and another for writing, and another interface for the "missing" functionality. Each user of your concrete class will then cast it to the interface it needs.

Implements interface java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is an interface in Java?
I have experience with object languages and object paradigm, but I have one doubt about "implements" statement. Doubt is does it includes code (functionality)? So to be very specific Does "MyClass implements XInterface" include code from other classes that implement that interface?
Class inheriting is simple including code, in a way, I know "including" may not be right word but that is what is talking place when you use "extends". You include functionality from parent class.
So let use Runnable interface for example. It has only one run() deceleration. Which could mean nothing, just that MyClass will have implementation of run(). And that what confuses me, like implementing one line deceleration in some file will make me some good... where is the actual functionality (and code) that I will get by using "implements"? So if I use:
MyClass implements Runnable {}
Runnable obj = new (Runnable) MyClass();
obj.run();//will call run() implementation from MyClass
obj.otherFunctions();/* so this calls functions from other classes that implement interface, but I don't know what functions from other classes are implementing, or even do I need them?*/
Also do I have to have one class per thread, like MyClass extends Thread implements Runnable ?
A class Cl that implements an Interface means that all methods that are defined in the interface must be implemented in class Cl. The calling class then can call these methods, because it is known that Cl implements (fullfills) the interface.
For example see the List interface: ArrayList and LinkedList both implement List, they have the same public methods (e.g add(), get()), but are internally working different.
List list = new ArrayList();
list.add(3);
later if somebody wants ArrayList to be exchanged by another class, that also implements List, only one line has to be exchanged
List list = new LinkedList();
list.add(3);
If programming to Interfaces the code is less dependent on a specific class. this has advantages when you later want to exchange one class for e,g purpose of testing, where you could controll that class by a test case.

java Queue interface polymorphism

I was reading http://www.docjar.com/html/api/java/util/LinkedList.java.html
When you declare a queue in Java
Queue<Integer> queue = new LinkedList<Integer>();
What happens behind the scene ? because I see queue is an interface with just method signatures, and LinkedList doesn't directly implement it, so how does it override those methods (add(), peek(), poll(), offer(), and remove() ) and do the polymorphism like that ? I mean you can only access some certain methods but not all of them from LinkedList for example public void add(int index, E element) is no longer available as it makes the apparent type to Queue. Also didn't we need to cast it ?
From the source code of the JDK:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
So LinkedList<E> doesn't directly implement Queue<E>, but it does implement Deque<E>, which extends Queue<E>:
public interface Deque<E> extends Queue<E> {
Threfore, LinkedList<E> inherits the abstract methods of Queue<E>.
The overriding methods are defined directly in LinkedList<E> - as usual.
because I see queue is an interface with just method signatures, and LinkedList doesn't directly implement it
LinkedList does implement a Queue: http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html
Refer this
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
LinkedList does implement Queue. When an object is declared using an interface, the compiler treats it solely as an object of that type. however, since you cannot instantiate an interface, you need to instantiate it as a class that implements that interface. In this case, you will not be able to access some of LinkedList's methods, (push(), pop(), for example), because the compiler identifies queue as a Queue<Integer>. However, since it was instantiated as a LinkedList<Integer>, and can be casted easily to a LinkedList.

How does Iterator ties into Collection Interface

I am new to Java.
Java has Collection interface
public interface Collection<E> extends Iterable<E>
{ // a lot of other stuff.
Iterator<E> iterator(); }
What I don't understand is how does Iterator Interface is tying into Collection Interface ? When I look at the Collection Interface, I see that it has a method that returns Iterator. When Iterator for Collection is created, where does JVM looks to create an object that IS-An Iterator ?
Thanks !
The JVM doesn't do it; the code that ultimately implements the abstract iterator() method just creates an instance of an appropriate class and returns it. For example, in the class ArrayList(), which implements List which extends Collection, there is a method that implements iterator() by returning an instance of a class that understand how ArrayList is implemented internally. This Iterator class is private to the java.util package -- normally you'll never see its name.
Ok so this is all pretty advanced java stuff and it will be pretty tough to explain in one go here but I will do my best.
BACKGROUND: If you don't know about those funny <E> things, you should do a bit of looking into Java Generics. Also, if you don't already, you really need to know what an interface is. One really basic way to think of it is as a promised bit of functionality a class promises to provide.
Now to answer your question: There are three interfaces in the above code snippet, and if you want to create your own collection class you will need to provide implementations of all three:
The first is Collection. This is a simple concept that maps to the real world, it is literally a "collection" of objects. I think you get this...
The next one is Iterable this defines a singe type of behavior that all collections need to provide: the ability to traverse all of the elements of a collection, while accessing them one by one ie "iterate" over them. But it doesn't stop there. As you pointed out the Iterable functionality is provided by objects that implement the last interface:
Iterator: objects that implement this interface, actually know how to traverse the elements of a collection class, they hide all the details of how its actually done from thier clients and proved a few clean easy methods for actually doing it like hasNext() which checks to see if there are more things in the collection to visit and next() which actually visits the next thing.
phew...
The code for the iterator() method determines which concrete implementation of Iterator to return.
All non-abstract classes that implement the Collection interface are required to provide an implementation for the iterator() method.

Categories