In C, that's true. Java is a little bit messier:
First, you've got
interface (language keyword)
files. Interfaces are very similar to .h
files in C, in that
they contain the signatures, and no implementation. Classes
then get to implement (language keyword) 0 to N
interfaces.
While you can not instantiate an
interface, you can instantiate a class
that
implements the interface, and a method can
expect an object
of the type of the interface.
However, here's the catch, the
interface gets
compiled
into a .class file just like regular classes.
Interfaces exist to permit some sort of multiple
inheritance (full
blown multiple inheritance is not allowed
in
Java)
Example
public interface
Comparable<T>
{
/*From the standard java API*/
public int
compareTo(T C);
}
public class Person implements Comparable
<Person>
{
<snip bunch of things relating to the
implementation of
the person: how they are created, what attributes they
have,...>
private float height;
/*getter for height*/
public float getHeight()
{
return height;
}
/*compareTo method for persons, uses height*/
public int compareTo(Person
p){
return this.height-p.getHeight();
}
Now,
you could have an array of Persons, and use any sorting
method to sort them
(such as timsort, probably) because most
sorting methods rely on the elements
to sort being
Comparable, the little <T> in the method declaration are
placeholders for the type, because this uses generics. This
means that you
could have an array of Comparable,
but you could not add a Building to it,
because Buildings
are Comparable. Also, you can't compare Persons to
Buildings, even if both are Comparable.
After this digression, let's
go back to the point:
Interfaces in Java can exist as real entities, because it
is
not until the virtual machine loads the bytecode and
translates it to
machine code/interprets it that their
presence becomes unnecessary. However,
not all interfaces in
an API are Interfaces, since it only makes sense to
create
Interfaces when you want to have type compatibility between
classes
that are not part of the same inheritance branch.
Now, it's a good practice to
have the API include Interfaces
for things where it's expected that the
programmers will
want to use their own stuff instead of using the stuff that
comes with the library.
Again, we have a conflict of
lawyerspeak and
geekspeak...[ Reply to This | Parent | # ]
|