Thread: interfaces
View Single Post
  #2 (permalink)  
Old April 23rd, 2007, 05:21 AM
AndrewH AndrewH is offline
Authorized User
 
Join Date: Nov 2005
Location: , , United Kingdom.
Posts: 15
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Java is a single-inheritance language which means each class can extend only one other class. This is because languages that are multi-inheritance languages such as C++ where you can make a class extend more than one other class are rather prone to subtle error as a result of this because multi-inheritance often leads to complex class hierarchies and name-clash errors and all sorts of horrible bugs. It is for this reason that java has been designed to be single-inheritance language.

But there are occasions where you would want a class to inherit the characteristics of more than one other class. This is when interfaces came to be useful; a class in java may only be allowed to extend one other class but a class in java can implement any number of interfaces. This creates a similar effect as multi-inheritance but, because of the severe constraints on what an interface can have, this multi-inheritance-like effect does not cause the usual complications that comes from true multi-inheritance.

Suppose you want a number of classes to inherit a method called getNoise() that returns a string that represents a ‘noise’ that objects of those classes are said to make. You could do this by making an interface called NoisyThing that has the public abstract method getNoise() and then you can make a number of classes such as ones named Dog and Cat and Gun etc implement the NoisyThing interface. These classes may otherwise be completely unrelated because, for example, the class Gun may be in a completely different class lineage from the class Cat in the single-inheritance class hierarchy.

The class Dog could be written as:

class Dog extends Animal implements NoisyThing{

//overrides the abstract method inherited from NoisyThing
    public String getNoise(){return “bark”; }

}

While the class Gun could be written as:

class Gun extends Weapon implements NoisyThing{

//overrides the abstract method inherited from NoisyThing
    public String getNoise(){return “bang”; }

}

Now it is possible to write a method, perhaps in some other unrelated class, that accepts an object of type NoisyThing as an argument and then invoke the getNoise() method on that object:

public static void printNoise( NoisyThing n ){
       System.out.println( n.getNoise() ); }

Then if you now call the above method with:

Dog d = new dog();

Gun g = new Gun();

…printNoise( d );
…printNoise( g );

Then the output to system.out will be:

bark
bang

The point is, given that java is a single-inheritance language, if you want to get this precise above behaviour from your java program and java did not have interfaces, then this would impossible. So this is an example of why java has interfaces.

            AndrewH:)

Reply With Quote