Monday, April 30, 2007

What is the difference between an abstract class and an interface?

An abstract class allows its subclasses to override the methods defined in it. It is never instantiated and a class can inherit from a single class, as Java doesn't support for Multiple Inheritance. It may contain both abstract and non-abstract methods.

An interface has public, abstract methods and may have public, static and final variables (read only). It introduces multiple inheritance by a class implementing several interfaces.

An example:



interface Movable
{
abstract move ();
}
abstract class Mammal
{
void getHeight(float height)
{ ... }
abstract eat();
}
abstract class Vehicle
{
void getSizeofSeat(float seatSize)
{ ... }
abstract engineType();
}
class Student extends Mammal implements Move
{
......
getheight(height);
void eat()
{.......}
void move();
}
class Car extends Vehicle implements Move
{
......
getSizeofSeat(float seatSize
void engineTypr()
{.......}
void move();
}

Hence Student and Car is not related but they can still implement the Move interface.

Moreover,an abstract class can have concrete methods while an interface cannot.

0 comments :

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker