Java: Interfaces

An interface may seem like a useless invention. Most assume it simply defines what methods are included in a class. However, that is not all it does, and the assumption is not entirely accurate. Keep reading to discover the how and why of interfaces.


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 three separate 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 separate class for testing in order to prove that it does not affect the interface’s ability to discern 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: 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: [email protected]
-William. § (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.

  • http://www.facebook.com/people/Joshua-Moore/668189180 Joshua Moore

    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!