What is the difference between an interface and ab

2018-12-31 02:16发布

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

30条回答
千与千寻千般痛.
2楼-- · 2018-12-31 02:32

An abstract class is a class whose object cannot be created or a class which cannot be instantiated. An abstract method makes a class abstract. An abstract class needs to be inherited in order to override the methods that are declared in the abstract class. No restriction on access specifiers. An abstract class can have constructor and other concrete(non abstarct methods ) methods in them but interface cannot have.

An interface is a blueprint/template of methods.(eg. A house on a paper is given(interface house) and different architects will use their ideas to build it(the classes of architects implementing the house interface) . It is a collection of abstract methods , default methods , static methods , final variables and nested classes. All members will be either final or public , protected and private access specifiers are not allowed.No object creation is allowed. A class has to be made in order to use the implementing interface and also to override the abstract method declared in the interface. An interface is a good example of loose coupling(dynamic polymorphism/dynamic binding) An interface implements polymorphism and abstraction.It tells what to do but how to do is defined by the implementing class. For Eg. There's a car company and it wants that some features to be same for all the car it is manufacturing so for that the company would be making an interface vehicle which will have those features and different classes of car(like Maruti Suzkhi , Maruti 800) will override those features(functions).

Why interface when we already have abstract class? Java supports only multilevel and hierarchal inheritance but with the help of interface we can implement multiple inheritance.

查看更多
谁念西风独自凉
3楼-- · 2018-12-31 02:34

If you have some common methods that can be used by multiple classes go for abstract classes. Else if you want the classes to follow some definite blueprint go for interfaces.

Following examples demonstrate this.

Abstract class in Java:

abstract class animals
{
    // They all love to eat. So let's implement them for everybody
    void eat()
    {
        System.out.println("Eating...");
    }
    // The make different sounds. They will provide their own implementation.
    abstract void sound();
}

class dog extends animals
{
    void sound()
    {
        System.out.println("Woof Woof");
    }
}

class cat extends animals
{
    void sound()
    {
        System.out.println("Meoww");
    }
}

Following is an implementation of interface in Java:

interface Shape
{
    void display();
    double area();
}

class Rectangle implements Shape 
{
    int length, width;
    Rectangle(int length, int width)
    {
        this.length = length;
        this.width = width;
    }
    @Override
    public void display() 
    {
        System.out.println("****\n* *\n* *\n****"); 
    }
    @Override
    public double area() 
    {
        return (double)(length*width);
    }
} 

class Circle implements Shape 
{
    double pi = 3.14;
    int radius;
    Circle(int radius)
    {
        this.radius = radius;
    }
    @Override
    public void display() 
    {
        System.out.println("O"); // :P
    }
    @Override
    public double area() 
    { 
        return (double)((pi*radius*radius)/2);
    }
}

Some Important Key points in a nutshell:

  1. The variables declared in Java interface are by default final. Abstract classes can have non-final variables.

  2. The variables declared in Java interface are by default static. Abstract classes can have non-static variables.

  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..

查看更多
呛了眼睛熬了心
4楼-- · 2018-12-31 02:34

You can find clear difference between interface and abstract class.

Interface

  • Interface only contains abstract methods.
  • Force users to implement all methods when implements the interface.
  • Contains only final and static variables.
  • Declare using interface keyword.
  • All methods of an interface must be defined as public.
  • An interface can extend or a class can implement multiple other interfaces.

Abstract class

  • Abstract class contains abstract and non-abstract methods.

  • Does not force users to implement all methods when inherited the abstract class.

  • Contains all kinds of variables including primitive and non-primitive

  • Declare using abstract keyword.

  • Methods and members of an abstract class can be defined with any visibility.

  • A child class can only extend a single class (abstract or concrete).

查看更多
大哥的爱人
5楼-- · 2018-12-31 02:34

To give a simple but clear answer, it helps to set the context : you use both when you do not want to provide full implementations.

The main difference then is an interface has no implementation at all (only methods without a body) while abstract classes can have members and methods with a body as well, i.e. can be partially implemented.

查看更多
泛滥B
6楼-- · 2018-12-31 02:35

Interfaces

An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way".

An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.

For example (pseudo code):

// I say all motor vehicles should look like this:
interface MotorVehicle
{
    void run();

    int getFuel();
}

// My team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{

    int fuel;

    void run()
    {
        print("Wrroooooooom");
    }


    int getFuel()
    {
        return this.fuel;
    }
}

Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.


Abstract classes

Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.

Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".

For example:

// I say all motor vehicles should look like this:
abstract class MotorVehicle
{

    int fuel;

    // They ALL have fuel, so lets implement this for everybody.
    int getFuel()
    {
         return this.fuel;
    }

    // That can be very different, force them to provide their
    // own implementation.
    abstract void run();
}

// My teammate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
    void run()
    {
        print("Wrroooooooom");
    }
}

Implementation

While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.

In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.

In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).

As usual with programming, there is theory, practice, and practice in another language :-)

查看更多
何处买醉
7楼-- · 2018-12-31 02:35

In short the differences are the following:

Syntactical Differences Between Interface and Abstract Class:

  1. Methods and members of an abstract class can have any visibility. All methods of an interface must be public. //Does not hold true from Java 9 anymore
  2. A concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface.
  3. A child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces.
  4. A child class can define abstract methods with the same or less restrictive visibility, whereas class implementing an interface must define all interface methods as public.
  5. Abstract Classes can have constructors but not interfaces.
  6. Interfaces from Java 9 have private static methods.

In Interfaces now:

public static - supported
public abstract - supported
public default - supported
private static - supported
private abstract - compile error
private default - compile error
private - supported

查看更多
登录 后发表回答