Transcript Interfaces

Interfaces
Interfaces
– An interface describes a set of methods:
• no constructors
• no instance variables
– The interface must be implemented by some class.
• 646 java classes implement one or more interfaces
– Let's begin with a simple interface.
Old MacDonald had a farm
– Interfaces have public method headings followed by
semicolons.
• no { }
– No methods are implemented:
• Some other will do it
public interface BarnyardAnimal
{
public String sound( );
}
One or classes will implement
an interface
– To implement an interface, you must have all method
specified exactly as written in the interface.
public class Cow implements BarnyardAnimal
{
public String sound( )
{
return "moo";
}
}
public class Chicken implements BarnyardAnimal
{
public String sound( )
{
return "cluck";
}
}
What is the output?
public class OldMacDonald
{
public static void main(String[] args)
{
BarnyardAnimal animalOne = new Cow( );
BarnyardAnimal animalTwo = new Chicken( );
System.out.println( "With a " + animalOne.sound() +
" " + animalOne.sound() + " here," );
System.out.println( "and a " + animalTwo.sound() +
" " + animalTwo.sound() + " there." );
System.out.println( "Here a " + animalOne.sound());
System.out.println( "there a " + animalTwo.sound());
System.out.println( "everywhere a " +
animalTwo.sound() + " " +
animalTwo.sound() + "." );
}
}
Interfaces
– Interfaces are used by Java in several ways.
•
event-driven programs
– They can also be used to specify class design.
• They list all the methods that you must implement
• You add instance variables and constructors