2015-12-09

posted Dec 9, 2015, 6:27 AM by Samuel Konstantinovich   [ updated Dec 9, 2015, 8:52 AM ]

Goal: Wrap up interfaces


If you cant check your grades fill out this form:

https://docs.google.com/a/stuycs.org/forms/d/1tbazkZEs4-5wPi0b0PKTyOAiwnHa6QyvU5ra8STW0ZU/viewform?usp=send_form


Using Interfaces:


To use an existing interface, you need to write “implements InterfaceName” after the class name.


public class className implements InterfaceName{

//class definition here

}


When a class implements interfaces, you are forced to write the methods from the interface in the class.


Writing Interfaces:


Writing interfaces are similar to writing classes. They are their own separate file and instead of writing “public class className”, you write “public interface InterfaceName”. The methods should only call its type, name, and parameters.

eg.


public interface InterfaceName{

String method1(String param1); //this is a method signature, just like abstract method signatures

int method2(double param2);

}

Interfaces only have constants and method signatures (NOT method bodies)

Technically they can contain only:
constants, 
method signatures, 
default methods, 
static methods,  
nested types.  (we didn't learn this yet)

When to use Interfaces vs Inheritance?
When we talk about abstract classes we are defining characteristics of an object type, specifying what an object is. You can only extend from one base class so you want to inherit from the class which most accurately defines what you are.

In the case of an interface we define a capability, we are talking about specifying what the object can do. You can implement as many interfaces as you need. 




Another Interface: The Iterable Interface

  • Iterable means something you can iterate through

    • For example, an array is iterable, it can be iterated through.

  • Iterable has one method: Iterator() which returns an iterator for a set of elements of type T

    • This can be used, for example, in an Enhanced For loop:

for(T a : c){ //where c is the iterator, and a is of type T

//do something to a

}


for(Integer i : listOfStuff){
//where listOfStuff is an ArrayList for example

//do something to i

}

  • An iterator is basically something that has a “Next” (So while there is another thing, keep going; it allows you to go through every item in something)

  • For example, in iterator can be made for a set of numbers, let’s say between 0 and 500000000:

    • for(int i: new IntegerIteratorThing(500000000)){}

      • where IntegerIteratorThing iterates through some number up to it, or whatever else you’d like

  • It can be made for any collection of things.

  • The enhanced for loops requires an Iterator. Any class that implements Iterable, can create an iterator. So only Iterable classes can use the enhanced for loop.

Comments