Saturday, October 14, 2006

Use of Interface class in Java

When we write an interface class, it should be always public. We can’t write private interface classes because there will be no use or can’t accomplish the purpose of writing it. As we know Java language supports only one inheritance of its parent class. We can’t inherit more than one class. For example,

We can write,
public class Civic extends Honda {}

We cannot write,
public class Civic extends Honda, CarAudio {}

In the above line Civic type car is created inheriting Honda class. Say, we want to use a method which resides in another class called CarAudio, which contains all the methods related to audio functions. In this case we can use an interface class called ICarAudio that contains all the methods related to audio functions, and this can be used to add the audio functions to the Civic class.

public class Civic extends Honda implements ICarAudio {}

Interface classes can be used for the purpose of multiple inheritances in Java programming language. But note an interface class should be defined with static or public scope.

Let me point of some facts about interface class.

1. interface class will contain the signature of the method without the implementation.

public void maxVol() {}

2. Any given class can inherit more than one interface, we can achieve multiple inheritance through this.

3. Any given class cannot instantiate an interface class.

4. Methods should be written public or abstract in an interface class. It doesn’t allow writing private methods.

5. Variables in an interface class should be public, static or final.

6. A class should use all the methods in an interface class if it inherits an interface class.

Above can be applied for C# also.

Cheers!

No comments: