wade-watt wade-watt - 4 years ago 85
Java Question

Are Interface and Abstract Methods similar in usage?

I read many links on Stack like this question and i decided to ask .

When i create a Abstract Shape Class in Java i think the Class must have a method to


I think there are two way .

public abstract class Shape
public abstract double getArea();

When i create extended class from Shape , I redefine getArea() in extended classes.

So can i create this hierarchy with using
like this ?

public interface Contain
public double getArea();

and create class like this :

public abstract class Shape implements Contain

Then redefine getArea() for extended class of Shape.

I am confused a little bit in there.

What is the best way to decide between Interface and Abstract Method in usage ?

Answer Source

In a round-about way, yes their usages are "similar". More so is the comparison between an abstract class and an interface.

An interface is a set of predefined method stubs that can be implemented within a class and overridden as seen fit without inheritance.

An abstract class is a class with defined values and methods that cannot be instantiated and is for the purpose of inheriting/extending without other non-abstract classes.

For instance, you could have an abstract class called Animals with methods that are fully written and defined with variables and data members as well, yet you must first extend this Animals class with, say...Lion class that is not abstract to be able to instantiate and use these methods and data members.

With interfaces, I'll use an example of a radio. You could have an interface called RadioSystem that has method stubs for changing frequencies, switching from FM to AM and vice versa, etc., which is then implemented into another class, say...CarRadio so that it already has all of the methods stubs and predefined functionalities defined, then as the programmer you just need to write these methods in a way that best suits the class they're implemented by.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download