Java: Interfaces

Contributor Icon Contributed by William_Wilson Date Icon March 1, 2006  
Tag Icon Tagged: Java programming

The how and why of interfaces


An interface may seem like a useless invention, it simply defines what methods are included in a class, but that’s not all it does, and not entirley acurate.

An interface includes methods that are similar between different objects, perhaps you have a Person object and a Dog object, to display a field within them you would have to typecast it to the specific class, this causes problems when many classes are involved, suppose you added a Cat object now you have 3 seperate cases, just to -for example- print the name. Interfaces allow you to treat objects the same based on similar information.

The interface will also force you to include all methods defined within it in every class that implements it.

I have written the example below including a seperate class for testing, as to prove that it does not affect the interface ability to deicern which object it is dealing with.

CODE Example:
main.java
public class main{
public static void main(String args[]){
main m = new main();
Person p = new Person("William",21);
Cat c = new Cat("Mr. Whiskers", 4);
Dog d = new Dog("Max",18);
//show all objects created properly
System.out.println(p + "\n" + c + "\n" + d + "\n");
//show all objects are treated the same as defined as lfi
m.printName(p);
m.printName(c);
m.printName(d);
}
public void printName(LivingThingInterface lfi){
System.out.println(lfi.getName());
}
}

Cat.java

public class Cat implements LivingThingInterface{
String name;
int age;
Cat(String n, int a){
name = n;
age = a;
}
public String getName() { return name; }
public String toString(){
return name + "," + age;
}
public boolean hasFur() { return true; }
}

Dog.java

public class Dog implements LivingThingInterface{
String name;
int age;
Dog(String n, int a){
name = n;
age = a;
}
public String getName() { return name; }
public String toString(){
return name + "," + age;
}
public boolean hasFur() { return true; }
}

Person.java

public class Person implements LivingThingInterface{
String name;
int age;
Person(String n, int a){
name = n;
age = a;
}
public String getName() { return name; }
public String toString(){
return name + "," + age;
}

public boolean hasJob() { return false; }
}

LivingThingInterface.java

public interface LivingThingInterface{
public String getName();
public String toString();
}

*NOTE that methods not listed in the interface can be written and used in any of the objects, but they must accessed by that class only, and are not universal.

Questions/Comments: william_a_wilson@hotmail.com
-William. ยง (marvin_gohan)

Previous recipe | Next recipe |
 
  • Short, sweet, and to the point. Nice work. A nice follow-up to this article would be explaining the use of "abstract" classes. Thanks for sharing!
blog comments powered by Disqus