Javatpoint Logo

in which situations we use interface and abstract classes?

By: mahesh*** On: Fri Apr 12 16:36:45 IST 2013     Question Reputation1 Answer Reputation0 Quiz Belt Series Points0  1Blank User
In realtime scenario where we use interfaces and where we use abstract classesUp1Down

 
Actually Interface and abstract class are used to just specify some contract/rules which will just show, how their sub classes will be.

Mostly we know that interface is a pure abstract.Means there you cant specify a single method with body.This particular point is the advantages of abstract class.Means in abstract class u have right to specify method with body and without body as-well.

So if u want to specify something about ur subclass, then u may go for interface.
But if u also want to specify something for ur sub classes and u want also ur class should also have some own method.Then in that case u may go for abstract class
Image Created2Down

By: [email protected] On: Fri Apr 12 20:00:09 IST 2013 Question Reputation3 Answer Reputation32 Belt Series Points0 35User Image
Are You Satisfied :10Yes10No
 
If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
Image Created5Down

By: [email protected] On: Mon Apr 15 16:59:42 IST 2013 Question Reputation0 Answer Reputation392 Belt Series Points0 392User Image
Are You Satisfied :4Yes6No
 
When the sub-types behaviour is totally different then you use an interface, when the sub-types behaviour is partially common and different with respect to the supertype an abstract class is used.

Interface:
public interface Vechile {
int numberOfwheels();

}

public class Car implements Vechile {

@Override
public int numberOfwheels() {
// TODO Auto-generated method stub
return 4;
}

}

public class Bycycle implements Vechile {

@Override
public int numberOfwheels() {
// TODO Auto-generated method stub
return 2;
}

}

Abstract class:
public abstract class Car {

int numberOfwheels()
{
return 4;
}

abstract int cost();
}


public class Tata extends Car {

@Override
int cost() {
// TODO Auto-generated method stub
return 3000;
}

public static void main(String[] args) {
Tata t=new Tata();
System.out.println(t.cost());
System.out.println(t.numberOfwheels());
}
}
Image Created0Down

By: [email protected] On: Fri Jul 31 10:04:11 IST 2015 Question Reputation0 Answer Reputation0 Belt Series Points0 0User Image
Are You Satisfied :0Yes0No