Interface and Abstract class difference

An interface can be used in such a way that we don't know the class of object assigned to a reference of that interface type until runtime. Can we use the abstract class in a similar way too?
The difference between an abstract class and interface can be listed as
1. Interface can not have implementation of any method
2. The usage of interface and class is one other difference
3. What other differences we have?

Yes an abstract class can be used in a similar way. The main issue with an abstract class is that you extend it and you can only extend one class so that can be a huge limitation that an interface does not give you.
Here's another one that is often overlooked: use both.
public abstract class SomeBaseClass implements Runnable {
  public abstract void someAbstractMethod();
  public void someMethodWithADefaultImplementation(){
    System.out.println("Hello!");
}Any class that extends SomeBaseClass (and is not abstract) will need to implement the run() method of the Runnable interface.

Similar Messages

  • Interfaces and abstract classes

    can anyone pls tell me where exactly an abstract class is used and where exactly an interface is to be used.
    i think the main difference between an abstract class and an interface is that an interface will have all the abstract methods whereas an abstract class can have one or more abstract methods--- if i am not wrong.
    anything to add? -- pls let me know on this....
    and also how they might be useful for us....

    Inheritance is the most popular feature of the OOP. By organising classes into class hierachy it gives an extra dimension to the encapsulation of abstract data types becauase it enables classes to inherit attributes/methods from other classes.
    There are two complementary roles of inheritance in OOP application.
    1. Specialisation: Extending the functionality of an existing class.
    2. Generalisation: Sharing commonality between two or more classes.
    So adding functionality by extending what exists at each level to create more specialized classes. This would create a hierarchy and would be helpful even later on in maintenance.
    Now when to have an abstarct class and when an interface. An interface just defines the basic functionality to be implemented by all the subclasses, though the way they are implemented may be different. e.g an interfaca animal can have all those functionalities common to all animals in basics but different in implementation. e.g all animals walk however some walk on two legs and some on four. All animals can see but they might have a different colour spectrum visible. So all such methods general but common can be in an interface.
    Abstract classes come into play at a more defined level e.g in an abstract class human though walk would be the same so implemented there and then but talking can be left abstract since there may be different languages involved.
    For more details refer to a good OOP book.

  • Interface and abstract class

    why we have constructor for abstract class and not for interface,

    When you call a constructor of a class which is extended by abstract class. It runs first the abstract class constructor and then child class constructor and initialize the member variables.
    while interface has no variable all final data so interface is no need to implement a constructor.
    Regards,

  • How to use interface and abstract class in the real time sennario ?

    how to validate password and reenter password fields in the struts through the xml files?

    Here is a modified dealForm.jsp that merges the 2 steps - both symbol submission and Yahoo convert is done by it. Play with it and add your DB code to it:
    <html>
    <head><title>IPIB Database Selection</title></head>
    <body bgcolor="#DFDFFF">
    <H1><CENTER>IPIB Database Selection</CENTER></H1>
    <font size=4>
    <%@ page language="java" %>
    <%@ page import="java.net.*,java.io.*,java.util.*" %>
    <%
    String symbol = request.getParameter("symbol");
    if (symbol != null) {
    String urlString = "http://finance.yahoo.com/download/javasoft.beans?SYMBOLS=" + symbol + "&format=ab";
    try {
    URL url = new URL(urlString);
    URLConnection con = url.openConnection();
    InputStream is = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();
    StringTokenizer tokenizer = new StringTokenizer(line,",");
    String name = tokenizer.nextToken();
    name = name.substring(1, name.length()-2);
    String price = tokenizer.nextToken();
    price = price.substring(1, price.length()-2);
    %>
    <p>
    Original line from yahoo <%= line %>
    </p> <p>
    Name: <%= name %>
    </p> <p>
    Price: <%= price %>
    </p> <p>
    Pub DB processing code from dealLoad.jsp here
    </p>
    <%
    } catch (IOException exception) {
    System.err.println("IOException: " + exception);
    } else { %>
    <form action="dealForm.jsp"method="GET">
    <p>Enter Symbol: <input size="20" name="symbol">
    <inputtype="submit" value="Submit">
    </p></form>
    <% } %>
    </font>
    </body>
    </html>

  • Interfaces vs abstract classes

    hi,
    i have some kind of general idea about interfaces and abstract classes.but what are the situations that are most suitable for use interfaces and abstract classes..if u have any idea pls help me
    thanx and best regards,
    Kelum

    BigDaddyLoveHandles wrote:
    Reason for using interfaces #17: dynamic proxies.
    import java.lang.reflect.*;
    interface Fooable {
    void f();
    void g(int x);
    class Foo implements Fooable {
    public void f(){ System.out.println("Foo.f()"); }
    public void g(int x){ System.out.format("Foo.g(%d)", x); }
    public class ProxyExample implements InvocationHandler {
    private Fooable target = new Foo();
    public static void main(String[] args) {
    Fooable fooable = (Fooable) Proxy.newProxyInstance(
    Fooable.class.getClassLoader(),
    new Class[] { Fooable.class },
    new ProxyExample());
    fooable.f();
    fooable.g(17);
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("Invoking: " + method.getName());
    return method.invoke(target, args);
    <cat position_relative_to_pigeons="among">
    Although libraries like ASM or CGLIB allow you to dynamically proxy classes, too
    </cat>

  • JSF annotations on interface or abstract class

    Hello,
    Can we use JSF 2 annotations like @ManagedBeans or @SessionScoped for interfaces and abstract classes? I mean, will it works if I implement an interface which declares some annotation(s) and the managed bean class itself doesn't have annotations?
    Thanks a lot!
    Oleg.

    Okey, an example:
    @ManagedBean
    public abstract class MyAbstractClass {
    public class MyClass extends MyAbstractClass {
    Does it work if I access MyClass by ValueExpression #{myAbstractClass} ? Will be MyClass automatically annotated with @ManagedBean?
    Best regards.
    Oleg.

  • Whats the difference between an INTERFACE and a CLASS?

    Whats the difference between an INTERFACE and a CLASS?
    Please help.
    Thanx.

    http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=%2Bforum%3A31&qt=Difference+between+interface+and+class

  • Hi all,Interface vs Abstract class

    Hi, All When We are going to use interface or an Abstract class,Can tell exactly
    Thanks in advance

    Interface class is used to contain methods that is to be defined by children classes. And abstract class, even though you can have all methods being abstract, but normally I would use this class for situation such as implement methods that are general enough to be used by the children classes and left others being abstract to be implemented by children classes later. I always think this relationship in a simple way:
    Abstract Class: Animal
    Interface : Leg, Tail, Hair, Feather, Head...
    Children classes: Tiger, Bird, etc.
    Thus, for class Animal class you can have methods such as:
    Abstract: canRoar, canSing, canFly, ...
    Non-abstract: isSleeping, isAlive...
    More example:
    Tiger extends Animal implements Leg, Tail, Head, Hair
    Bird extends Animal implements Leg, Feather, Head
    I could be wrong, correct me if so. Cheers.

  • Can interface extend abstract class?

    Can interface extend abstract class?
    I tried to make a interface extend an abstract class but i got an error stating:
    interface expected here.
    Can anyone help me ?

    > ok, but can an interface implement an abstract class?
    No. An interface provides no implementation whatsoever. An abstract class can implement an interface, but not the other way around.
    http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
    ~

  • Abstract classes, Interfaces, and concrete classes

    I have another technical interview tomorrow and somehow I keep getting asked the same question and I feel my answer is not really up to par. The question is:
    "What is the advantage of subclassing an abstract class versus concrete class?"
    "What is the difference of using an interface versus an abstract class, which is better to use?"
    For the first question, I usually answer performance is the advantage because you don't have to instantiate the class.
    For the second question, I usually say that you can put implementation in an abstract class and you can't in an interface. I really can't answer the second part to this question.
    Any ideas?

    For the first question, I usually answer performance
    is the advantage because you don't have to instantiate
    the class. Try invoking the class B in the following somewhere in another class.
    abstract class A{
       A(){
          System.out.println("abstract instantiated");
    class B extends A{
      B(){super();}
    }

  • Difference between inheritance and abstract class

    difference between inheritance and abstract class

    See this thread:
    http://forum.java.sun.com/thread.jspa?forumID=24&threadID=663657
    And before Post New Topic, just search in this forums. All most will get answers.

  • Help with interface and abstract

    Hi all
    what is the difference between an interface and an abstract class??

    Suppose if you want to implement all the methods we usually use the interface. if you define a method in the interface you must provide the implementation for this interface in the implementation class.
    In case of abstract, we can have both the abstract and non -abstract methods. Means abstract class can have the methods with the implementations defined in that class and abstract methods which needs to be implemented for the sub classes.

  • Inter face and abstract class

    hi
    can u please tell me the difference between interface and an abstract class? In which situations they will be usefull.
    thank u
    shyam

    http://java.sun.com/developer/JDCTechTips/2001/tt1106.html#tip2

  • Nested interfaces and abstract methods

    Consider the following design:
    interface ZIF_INTERFACE_A.
      methods METHOD_A.
    endinterface.
    interface ZIF_INTERFACE_B.
      interfaces ZIF_INTERFACE_A.
      methods METHOD_B.
    endinterface.
    class CLASS_A_B definition abstract.
    public section.
      interfaces ZIF_INTERFACE_B
        abstract methods METHOD_B.
      interfaces ZIF_INTERFACE_A
        abstract methods METHOD_A.
      methods METHOD_C.
    endclass.
    class CLASS_A_B implementation.
      method METHOD_C.
      endmethod.
    endclass.
    When trying to implement this design, the syntax check is giving me an error:
    The method "METHOD_A" was declared as not ABSTRACT in a previous INTERFACES statement.
    If I implement the design with Java (either using a public nested interface, or using interface inheritance) there is no problem declaring both the methods METHOD_A and METHOD_B as abstract in the CLASS_A_B class.
    So it seems to me this might be a bug in the ABAP Objects implementation. Or perhaps I am missing something else here? Does anyone have any suggestions?

    Hello,
    Nested interfaces
    When you include an IF in another IF both of them will exist on the same level, there is no concept of hierarchy. So when you add interface ZIF_B in the implementing class ZCL_A_B, the interface ZIF_A is also "included" in the relationship with the class ZCL_A_B implicitly.
    Just try to activate the code below & you'll get the error: "Implementation missing for method zif_interface_a~method_a":
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
    *    INTERFACES zif_interface_a
    *      ABSTRACT METHODS method_a.
        INTERFACES zif_interface_b
          ABSTRACT METHODS: method_b.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
        INTERFACES zif_interface_b
          ABSTRACT METHODS method_b.
        INTERFACES zif_interface_a
          ABSTRACT METHODS method_a.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    So when the compiler is trying to compile your code it encounter implementation of ZIF_INTERFACE_B it finds that the "included interface" method ZIF_INTERFACE_Amethod_a is not abstract. So when you declare ZIF_INTERFACE_Amethod_a as "abstract" in the next line the compiler throws this error.
    So you need to define ZIF_INTERFACE_A~method_a as abstract, before defining ZIF_INTERFACE_B. Like this:
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
        INTERFACES zif_interface_a
          ABSTRACT METHODS method_a.
        INTERFACES zif_interface_b
          ABSTRACT METHODS method_b.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    In this case the compiler treats method_a as abstract while checking ZIF_INTERFACE_B. Hence it doesn't throw any error.
    Hope i'm clear.
    BR,
    Suhas
    PS: Whenever i face any problem while creating local classes, i create a dummy class in the class builder to check

  • Interface and Inner Class

    Hi,
    In interface we can't provide method body.
    but we can provide method body like this,
    public interface TestInterface {
         public class Add {
              public int add() {
                   return 100;
    what is the logic behind Inner Class inside interface.
    plz help.Thanks in advance.

    there isn't really any logic to it, it's just something that's semantically possible. there wasn't a conscious decision to allow this, it's just a by-product of the enclosing types mechanism, and while it wouldn't be a good idea to do this, there's no technical reason why it shouldn't be possible, either

Maybe you are looking for

  • Random Artifact and "Could not save (file name) because the file is already in use or left open."

    Hi, I've been working on a collage for school, and I 'merged all layers below into one layer', and photoshop left me a random artifact on all my masks. Also, the same file has been suffering the 'Could not save...' problem. I have taken older version

  • What is use of asteric sign in oracle

    Updat TableA Tout set col3,col4 = (select col3,col4 from TableA Tin where Tin.col1=Tout.col1 and Tin.col2=Tout.col2 and Tin.coln=*'B'* ) where coln=*'A'

  • New to iweb

    every time i open i web it does not pull up the template pages... i have subsricbed and everything. i can't even add a page. help? does anyone have any answers?

  • Ungroup text in Illustrator?

    What is the purpose of ungrouping text in Illustrator? Once the text has been ungrouped, can it be reverted back to text? Thanks.

  • Loading Smart list values

    Hi All, Can we load smart list values thirugh FDQM? I have tried but it gives error during import stage. Any help will be highly appreciated. Thanks in advance.