Title: Java: Interfaces Post by: Khushi on January 03, 2007, 12:01:25 AM 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 Code: public class main{ Cat.java Code: public class Cat implements LivingThingInterface{ Dog.java Code: public class Dog implements LivingThingInterface{ Person.java Code: public class Person implements LivingThingInterface{ LivingThingInterface.java Code: public interface LivingThingInterface{ *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. |