interfaces Flashcards
polymorphism
many forms (when code looks the same, but behavior differs)
ArrayStoreException
what we get if we attempt to store an object of type X in an array of type Y
(remember: array lists have a homogenous data structure)
interface
establishes a set of public methods that any class which implements that interface must contain
ALL METHODS ARE PUBLIC STATIC
ALL VARIABLES ARE PUBLIC STATIC FINAL
Comparable
> an interface that is defined by the standard Java libraries > a class that implements comparable interface needs public method: int compareT (T otherObject) >has one method : compareTo
Arrays.
just like math. java has a utility class named Arrays that contains a variety of general-purpose methods
Arrays.sort()
takes any array of an object type as long as that type implements the Comparable interface
> negative number if parameter comes before method
> zero if parameter equals method
> positive number if parameter comes after method
how to implement comparable interface
public class Rational implements Comparable {
@override
key word for interfaces (causes a compilation error if the signature of the class method doesn’t match the signature of the interface method) (not required, because there are no differences behind the scenes)
how to implement an interface
public class Cat implements Animal {
how many interfaces can a class implement
as many as you want
heterogeneous array / array list!!!
if we make an array of animal references, it can have dog and cat objects
why interfaces need casting:
We can use (type)casting to specify what the object’s actual data type is and then we can dereference it using that to gain access to non-interface methods
what if you want an animal interface to also be a comparable interface?
a newly-defined interface can extend an existing one:
public interface ComparableAnimal extends Comparable {
what if you only wanted some of your animals to also be comparable?
public class ComparableCat implements Animal, Comparable {
default method
allowed to have a default implementation of a method within the interface definition itself
default public String makeSound(){ return “um”; }