Interfaces in java, Really Needed?

Most of the newcomers in java programming language experience a confusion why on earth do you need Interfaces when you have abstract classes. It is one of the simple feature of java that may sometimes become puzzling. Interfaces are necessary for multiple implementation inheritance which means child class inheriting from multiple parent classes which is not possible through abstract class. Simply we can say that a class in java can extend only one abstract class at once but can implement multiple Interfaces at once. In this regard we have to know that interfaces are not actually the classes.

In the below example we are implementing two interfaces in a single class. The Child class implements two interfaces First and Second.

 


interface First{

int rate=4;

void getInstallment();

//no access modifier because the methods in interface are always public

}

interface Second{

double weight =4.5;

void getFare();

}

class Child implements First, Second{

public void getInstallment(){

int total = rate*500;

System.out.println("The total is: "+total);

}

public void getFare(){

double totalfare = weight*100;

System.out.println("The total fare is: "+totalfare);

}

}

public class MainClass{

public static void main(Strin[] args){

Child obj = new Child();

System.out.println(" "+obj.getFare()+" "+obj.getInstallment());

}

}

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s