Difference b/w interface and a class

Difference b/w interface and a class

Difference b/w interface and a class used in android with examples….the example will clear the use of these two and where to use a interface or a class

The key technical differences between an abstract class and an interface are:

  • Abstract classes can have constants, members, method stubs and defined methods, whereas interfaces can only have consts and methods stubs.
  • Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.
  • When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an an abstract class can extend another abstract class and abstract methods from the parent class don’t have to be defined.
  • Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
  • A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.
  • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility.

Interfaces

An interface is an empty shell, there are only the signatures (name / params / return type) of the methods. The methods do not contain anything. The interface can’t do anything. It’s just a pattern.
Implementing an interface consumes very little CPU, because it’s not a class, just a bunch of names, and therefore there is no 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.

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).

About the author

admin administrator

Leave a Reply