My Java Tutorials - Interfaces
Here is some example code....
Copy and paste it to your page if you wish to use it.
interface Fruit {
public boolean hasAPeel();
//has a peel must be implemented in any class implementing Fruit
//methods in interfaces must be public
}
interface Vegetable {
public boolean isARoot();
//is a root must be implemented in any class implementing Vegetable
//methods in interfaces must be public
}
class FandVUtility {
static String doesThisHaveAPeel(Fruit fruitIn)
{
if (fruitIn.hasAPeel())
return "This has a peel";
else
return "This does not have a peel";
}
static String isThisARoot(Vegetable vegetableIn)
{
if (vegetableIn.isARoot())
return "This is a root";
else
return "This is not a root";
}
static String doesThisHaveAPeelOrIsThisRoot(Tomato tomatoIn)
{
if (tomatoIn.hasAPeel() && tomatoIn.isARoot())
return "This both has a peel and is a root";
else if (tomatoIn.hasAPeel() || tomatoIn.isARoot())
return "This either has a peel or is a root";
else
return "This neither has a peel or or is a root";
}
}
class Tomato implements Fruit, Vegetable {
boolean peel = false;
boolean root = false;
public Tomato() {}
public boolean hasAPeel() //must have this method, because Fruit
declared it
{
return peel;
}
public boolean isARoot() //must have this method, because Vegetable
declared it
{
return root;
}
public static void main(String[] args) {
//Part one: making a tomato
Tomato tomato = new Tomato();
System.out.println(FandVUtility.isThisARoot(tomato));
//output is: This is not a root
System.out.println(FandVUtility.doesThisHaveAPeel(tomato));
//output is: This does not have a peel
System.out.println(FandVUtility.doesThisHaveAPeelOrIsThisRoot
(tomato));
//output is: This neither has a peel or or is a root
//Part two: making a fruit
//Fruit = new Fruit(); //can't instantiate an interface like this
because Fruit isn't a class
Fruit tomatoFruit = new Tomato(); //can instantiate by interface
like this because Tomato is a class
//System.out.println(FandVUtility.isThisARoot(tomatoFruit));
//can't treat tomatoFruit as a Vegetable without casting it to a
Vegetable or Tomato
System.out.println(FandVUtility.doesThisHaveAPeel(tomatoFruit));
//output is: This does not have a peel
//System.out.println(FandVUtility.doesThisHaveAPeelOrIsThisRoot
(tomatoFruit));
//can't treat tomatoFruit as a Vegetable without casting it to a
Vegetable or Tomato
}
}