sabaTEL.net

Java, MySQL, Avaya

Differences between abstract Class and Interface

Both try to achieve abstraction in Java but there are some fundamental differences between them:

  • An interface it’s an empty shell, there are only signatures of the methods, they are not implemented. The interface is just a pattern, a ‘contract’ established about what it can do without saying how to do it.
  • Abstract classes can have members, abstract methods (not implemented) and methods, using any visibility. Interfaces can have members and method declarations and all of them must be public.
  • 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 public visibility.
  • If we add a new method to an interface, that breaks the established contracts with all classes that implement it, so the method implementation will need to be added to all those classes. Adding a new method to an abstract class it’s not such a big deal, because we can always define default behaviour.

Maybe, I have confused you now, so probably best to look at very simple examples:

As you can see from the above, for an abstract class we can have abstract and non abstract methods living together, the only requirement is that the class has the abstract attribute in front of it.

With interfaces we know that the implementation of any of the methods is not allowed. So you should never see a ‘{ }’.

Advertisements

June 30, 2013 - Posted by | Java

1 Comment »

  1. My thoughts go out to you and James, on this day, Charles. I know, so difficult, and words are inadequate to convey my feelings and thoughts. Click https://twitter.com/moooker1

    Comment by chavezfarmer22858 | April 8, 2016


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

%d bloggers like this: