Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎notes‎ > ‎

2017-11-20

posted Nov 20, 2017, 9:22 AM by Konstantinovich Samuel   [ updated Nov 20, 2017, 10:27 AM ]
Goal: Interfaces!
Do Now:

On github.com :

1. Create a repo with a readme named: MKS21X
2. Clone the repo.
3. Make a directory 03WordSearch, and place your wordsearch java file in it!
4. Add , commit, push.

Show your neighbors your repo to verify this.
5. Submit your repo here:

You should now add the following directories (and their respective files)

01SuperArray/SuperArray.java
02OrderedSuperArray/OrderedSuperArray.java
02OrderedSuperArray/SuperArray.java    (This is needed for Ordered to compile)



Classwork:

Interfaces

In real life, objects have interfaces like buttons and switches.
In java, methods form an object's interface with the outside world.

In java:
Interfaces in Java allow us to create a collection of methods to guarantee a class's interaction. 
An interface does not contain method implementation, constructors, or instance variables.
The keyword interface is used to define this collection of methods.

Interfaces are often named as an adjective. Some are nouns (see List in java) but
the idea that the adjective can describe what it can do is more in the spirit of what an interface is.
Examples of adjective interface names: cloneable, comparable, runnable
( or the fictional ones like: smashable , killable, fixable, etc)

Example of creation of an interface:

public interface Washable 
 
  void mop(); 
  void scrub(int times); 
  void scrape(int times); 
}

class Floor implements Washable
   // The compiler will now require that methods
   // mop, scrub, and scrape
   // all be implemented. Compilation will fail if those
   // methods are missing from this class.
}
The last AP had the students write an interface. We won't write a lot of them, you need to know it.

Abstract classes vs Interfaces:

An abstract class’s purpose is to provide a superclass from which other classes can inherit and thus share a common design. 
This CAN include instance variables, and some concrete methods.
Abstract classes:
1. let you define some behaviors; and force your subclasses to provide others. 
2. are an excellent way to create planned inheritance hierarchies, as they are a good choice for non-leaf classes.
3. Limit a class to extend ONE abstract class.

Interfaces do not have any implementation. They are not classes, and cannot have any instance variables.
1. They are good when you want unrelated classes to share a behavior. 
2. They allow a single class to implement multiple behaviors. e.g. both Breakable and Fixable

Interfaces you should be aware of:
List
Comparable
Cloneable
Comments