Abstract method in Interface

Why are we able to define abstract method in an Interface?
I don't imagine when I must use an abstact method in a interface.
Does anybody ever use this?

Thanks for your answer.
I can declare an abstract class which implementes an
interface.
The abstract class doesn't require the implementation
of the methods
declared in the interface.
Why this?Because the class is abstract.
A concrete class must provide (or inherit) implementations for all abstract methods in all its ancestor classes and for all methods in all interfaces it implements (and remember, all methods in an interface are abstract).
If a class does NOT have an implementation for one or more of those methods, the class must be declared abstract to indicate that.
I don't understand because an abstract class can
implements an interface!Any class can be declared abstract (except final classes, I think).
Any class that doesn't have implementations for all its methods (including those from interfaces) MUST be declared abstract.

Similar Messages

  • Abstract methods in interface?

    hi, i dun feel that an interface can have abstract methods although the compiler doesn't complain. but i still see developer declares abstract methods in the interface. any clarification on this? thx
    cy

    hi, i dun feel that an interface can have abstract
    methods although the compiler doesn't complain. but i
    still see developer declares abstract methods in the
    interface. any clarification on this? thx
    cyThose developers are just a bit verbose, all methods in an interface are public and abstract.
    Kaj

  • Abstract methods of Interface

    Methods of an interface can be abstract or non abstract ( correct me if i am wrong ) . What is the use in making an Interaces method abstract ?.
    public interface MyInterface {
    public abstract String validate(String id );
    }thanks in adavnce .

    All methods in an interface definition are, by definition of the language, abstract.
    It's just that the compiler allows you to type the keyword 'abstract' if you want to.
    kind regards,
    Jos

  • Abstract class and interface having same method

    Hello,
    Here is my problem. Suppose we have one abstarct class and one interface.Here is code-
    //Abstarct class
    abstract class X{
    abstract void myMethod();
    //Interface
    public interface Y{
    abstract void myMethod(){}
    Now i have a class which extends both abstarct class X and interface Y.
    If i call myMethod() from this class. Whose myMethod would be called.Will it be of abstract class or interface?
    Many Thanks

    Hello,
    Here is my problem. Suppose we have one abstarct class
    and one interface.Here is code-
    //Abstarct class
    abstract class X{
    abstract void myMethod();
    }OK, so far...
    //Interface
    public interface Y{
    abstract void myMethod(){}
    }An interface cannot have code (the {} part), so this won't work.
    Lets pretend though, it read
    //Interface
    public interface Y{
    abstract void myMethod();
    However, the abstract class above can have code;
    If you extended X and implemented Y (with no code in it), you would have to have a myMethod() implementation in your code. That's the one that would run.
    Now, let's pretend the abstract class above did have code in it.
    //Abstract class
    abstract class X {
    abstract void myMethod() { System.out.println("Hello"); }
    Then, you wouldn't have to have a myMethod() implementation in your class which extends X and implements Y (it's defined in X). If you didn't have one, the method in X would run. If you defined your own myMethod() implementation in your class (which extends X and implements Y), then your own implementation would run.

  • 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

  • Should @Override apply to implementation of interface/abstract methods?

    To me this is a minor but irritating incompatibility between Java 5 and 6. In 5 the @Override annotation only applied when an actual concrete method was overridden. In 6 it also applies when an interface or abstract method is implemented.
    To my mind only the first case is actually overriding. Further the purpose of the @Override, AFAIKS, is to catch errors where you accidentally override a method, or write a method which you expect to override another, but get the signature wrong.
    This kind of error isn't going to happen on implementing a method because you will get a real syntax error.
    If we were going to use annotations to guarantee implementation it should be @Implements

    sabre150 wrote:
    masijade. wrote:
    Having spend some time recently changing from extending abstract classes to implementing interfaces I would hate to have two different annotations!It would be annoying, yes, in that case, but it would still be more "technically" correct to have a different tag. And, if we are going to insist that "newbies" here at least attempt to adhere to standards/procedures/whatever, we should be willing to do the same. ;-)It would be more "technically" correct to have an 'override' key word in the same way as in C# . The annotation approach is used to make up for a deficiency in the language specification. If one applies the KISS principle or the 'principle of least surprise' then just having one annotation makes sense.Okay then, we agree to disagree. But getting even farther away in the "use" of the term as opposed to the "definition" of the term isn't helping to make up for the deficiency in the language.
    Of course, in the practical sense it is better to have one as it is, then, least likely to "break" in a backwards compatability sense (even when it only applies to compilation and not execution).

  • ...is not abstract and does not override abstract method compare

    Why am I getting the above compile error when I am very clearly overriding abstract method compare (ditto abstract method compareTo)? Here is my code -- which was presented 1.5 code and I'm trying to retrofit to 1.4 -- followed by the complete compile time error. Thanks in advance for your help (even though I'm sure this is an easy question for you experts):
    import java.util.*;
       This program sorts a set of item by comparing
       their descriptions.
    public class TreeSetTest
       public static void main(String[] args)
          SortedSet parts = new TreeSet();
          parts.add(new Item("Toaster", 1234));
          parts.add(new Item("Widget", 4562));
          parts.add(new Item("Modem", 9912));
          System.out.println(parts);
          SortedSet sortByDescription = new TreeSet(new
             Comparator()
                public int compare(Item a, Item b)   // LINE CAUSING THE ERROR
                   String descrA = a.getDescription();
                   String descrB = b.getDescription();
                   return descrA.compareTo(descrB);
          sortByDescription.addAll(parts);
          System.out.println(sortByDescription);
       An item with a description and a part number.
    class Item implements Comparable     
          Constructs an item.
          @param aDescription the item's description
          @param aPartNumber the item's part number
       public Item(String aDescription, int aPartNumber)
          description = aDescription;
          partNumber = aPartNumber;
          Gets the description of this item.
          @return the description
       public String getDescription()
          return description;
       public String toString()
          return "[descripion=" + description
             + ", partNumber=" + partNumber + "]";
       public boolean equals(Object otherObject)
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)
             && partNumber == other.partNumber;
       public int hashCode()
          return 13 * description.hashCode() + 17 * partNumber;
       public int compareTo(Item other)   // OTHER LINE CAUSING THE ERROR
          return partNumber - other.partNumber;
       private String description;
       private int partNumber;
    }Compiler error:
    TreeSetTest.java:25: <anonymous TreeSetTest$1> is not abstract and does not over
    ride abstract method compare(java.lang.Object,java.lang.Object) in java.util.Com
    parator
                public int compare(Item a, Item b)
                           ^
    TreeSetTest.java:41: Item is not abstract and does not override abstract method
    compareTo(java.lang.Object) in java.lang.Comparable
    class Item implements Comparable
    ^
    2 errors

    According to the book I'm reading, if you merely take
    out the generic from the code, it should compile and
    run in v1.4 (assuming, of course, that the class
    exists in 1.4). I don't know what book you are reading but that's certainly incorrect or incomplete at least. I've manually retrofitted code to 1.4, and you'll be inserting casts as well as replacing type references with Object (or the erased type, to be more precise).
    These interfaces do exist in 1.4, and
    without the generics.Exactly. Which means compareTo takes an Object, and you should change your overriding method accordingly.
    But this raises a new question: how does my 1.4
    compiler know anything about generics? It doesn't and it can't. As the compiler is telling you, those interfaces expect Object. Think about it, you want to implement one interface which declares a method argument type of Object, in several classes, each with a different type. Obviously all of those are not valid overrides.

  • Product is not abstract and does not override abstract method

    Received the following errors.
    Product.java:3: Product is not abstract and does not override abstract method ge
    tDisplayText() in Displayable
    public class Product implements Displayable
    ^
    Product.java:16: getDisplayText() in Product cannot implement getDisplayText() i
    n Displayable; attempting to use incompatible return type
    found : void
    required: java.lang.String
    public void getDisplayText()
    ^
    2 errors
    Code reads as follows
    import java.text.NumberFormat;
    public class Product implements Displayable
         private String code;
         private String description;
         private double price;
         public Product()
              this.code = "";
              this.description = "";
              this.price = 0;
    public void getDisplayText()
    String message =
    "Code: " + code + "\n" +
    "Description: " + description + "\n" +
    "Price: " + this.getFormattedPrice() + "\n";
         public Product(String code, String description, double price)
              this.code = code;
              this.description = description;
              this.price = price;
         public void setCode(String code)
              this.code = code;
         public String getCode(){
              return code;
         public void setDescription(String description)
              this.description = description;
         public String getDescription()
              return description;
         public void setPrice(double price)
              this.price = price;
         public double getPrice()
              return price;
         public String getFormattedPrice()
              NumberFormat currency = NumberFormat.getCurrencyInstance();
              return currency.format(price);
    Please help!

    Received the following errors.
    Product.java:3: Product is not abstract and does not
    override abstract method ge
    tDisplayText() in Displayable
    public class Product implements Displayable
    ^
    Product.java:16: getDisplayText() in Product cannot
    implement getDisplayText() i
    n Displayable; attempting to use incompatible return
    type
    found : void
    required: java.lang.String
    public void getDisplayText()
    ^
    2 errors
    Code reads as follows
    Please use the code tags when posting code. There is a code button right above the text box where you enter your post. Click on it and put the code between the code tags.
    These error messages are quite clear in telling what is wrong. You have an Interface called Displayable that specifies a method something like thispublic String getDisplayText() {But in your Product source code, you created thismethodpublic void getDisplayText() {The compiler is complaining because the methods are not the same.
    You also need to return a String in the method probalby like thisreturn message;

  • ABAP OO Abstract Methods

    Hi,
    I want to use abstract methods in ABAP. I created an abstract class as base and another 'child' class that extends that class. Now, I want to have different implementations in different child classes. The problem is that the IDE redirects me to the base class when trying to to this. There is no possibility to set the method as abstract.
    Do you know if that concept is implemented at all? Maybe I just forgot to configure something?!
    What do you propose?
    Thank you and best regards,
    Daniel

    Hi,
    If you are creating Local class using SE38, then just by writing "abstact" to the method it behaves like an abstract method.
    If you are creating global class SE24, then genrally all interface methods are "abstract" methods so that we can ihberit and can redefine the methods for example: "IF_FLUSH_NOTIFY~BEFORE_FLUSH_NOTIFY" symbol ~ shows that it is an abstract method in the interface before to that.
    So, even if it refer to its base class you can just implement them in the child classes by inheriting it.
    Hope this helps you if yes try to assign some app. points.
    Regards,
    Suman

  • Non-abstract methods in a Abstract class

    Abstract Class can contain Non-abstract methods.
    and Abstract Classes are not instantiable as well
    So,
    What is the purpose of Non-abstract methods in a Abstract class.
    since we can't create objects and use it
    so these non-abstract methods are only available to subclasses.
    (if the subclass is not marked as abstract)
    is that the advantage that has.(availability in subclass)
    ??

    For example, the AbstractCollection class (in
    java.util) provides an implementation for many of the
    methods defined in the Collection interface.
    Subclasses only have to implement a few more methods
    to fulfill the Collection contract. Subclasses may
    also choose to override the AbstractCollection
    functionality if - for example - they know how to
    provide an optimized implementation based on
    characteristics of the actual subclass.Another example is the abstract class MouseAdapter that implements MouseListener, MouseWheelListener, MouseMotionListener, and that you can use instead of these interfaces when you want to react to one or two types of events only.
    Quoting the javadocs: "If you implement the MouseListener, MouseMotionListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about."

  • Abstract method which when implemented will have different parameters

    Hello to all,
    I have an assignment but not looking for someone to do it for me. I am only searching for a suggestion on how to do the following.
    Imagine having an application that needs to provide an estimate of the rent for different buildings.
    Basically I start with by having a class name Building. This class has an abstract method called estimateRent.
    I then create two classes that extend the class Building which are named Apartment and House. Both need to have the method estimateRent.
    However the problem is that the rent for the Apartment is calculated on the nights passed in the flat and the people in it, while the rent for the House is just calculated on a month bases.
    This means the estimateRent method requires to have different parameters depending if it is implemented inside the Apartment class or the House class.
    Now I only know of two options.
    The first option is to not declare the estimateRent method as an abstract method inside the Building class and just implemented inside the Apartment and House with different parameters. I do not like this option since in the future if a new Building comes in then I would like to impose the fact that that object needs to have a calculate method.
    The second option is to make the estimateRent method as abstract inside the Building class however takes a parameter of either a String array or else a Map. Then the estimateRent within the Apartment class would search for the elements tagged as nights and people, and the House class would only search for the elements tagged as months!
    However do not know if there are any other, better ways on how to do this. I am using Java 1.4 however if you only have answers for Java 5.0 then please post them again since I always like to learn something new :)
    Thank You for any comments.
    tx

    The implementation changes, yes.Yes that I could understand in the Strategy Pattern (in the document I read it was being compared with the Template Pattern).
    Then you need to refactor your design.I tought about that, however if you read my first post you will notice that I have different criteria on which the costs need to be estimated. While the costs for a flat are estimated on the people staying in and nights slept there, the costs for the house are based only on the months stayed there regardless of the people living in. Now for me I feel that it is bad programming practice to create one method that can have all the parameters required for any scenario. I mean the following is NOT something I am going to do:
    estimateCosts(int nights, int people, int months ... etc);
    That's not a very elegant way of going about it.
    What is the "Context" going to have?Yep I agree, but so far my limited brain has only come up with that! I am open to any other sugestion! always if i understand it first!
    Basically the Context would better be named as Criteria and it would be an interface as follows:
    interface Criteria{}
    Then I would create two classes that implement the Criteria object as follows:
    class AppartmentCriteria implements Criteria{
    public Result estimateCosts(int nights, int people);
    class HouseCriteria implements Criteria{
    public Result estimateCosts(int months);
    Now when I recieve the inputs, depending on the scenario the Criteria is typecasted and the correct parameters passed and we recieve the Result.
    I feel the above sucks since I am not seeing it as an object oriented way of doing this out! Is there any other sugestions! The refactoring thing I am intrested in! however really I can not see how such a call to that method could be refectored!
    Thank You,
    tx.
    PS: Sun has blocked my other account as well, and this time they did not even send me an email to confirm that I was registered successfuully :( Is there someone I can contact on this? I guess next time I will reply with tx53m :)

  • Abstract Method Overriding Problem

    I have an abstract class called "Employee" with an abstract method called "ReturnBasicInfo()" defined.
    I have two subclasses, SalariedEmployee and HourlyEmployee, and each has their own version of ReturnBasicInfo(). The compiler is not letting me do this, however, and I have no idea why.
    I keep getting this error:
    SalariedEmployee.java:6: SalariedEmployee is not abstract and does not override
    abstract method returnBasicInfo() in Employee.The abstract method signature is this:
    public abstract String returnBasicInfo(Employee e);Any idea why this might be happening? I have another abstract method called toVector() that's overriden in the subclasses and that one works fine, so I'm stumped on this. The only difference between the two is that this method takes arguments and the other doesn't. Is that why it can't be overriden?
    Thanks in advance for any help!

    "...In the instructor's example code, he actually
    overrode toString with this method. I thought I might
    be using the real toString(), though, so that's why I
    changed the name to returnBasicInfo(). I didn't end up
    using toString(), though. Maybe I ought to go back to
    calling it toString()..."
    Yes, this SHOULD be overridden in toString(). Do go
    back to it.
    The "real" toString()? Do you mean the default
    version in java.lang.Object, the one that just prints
    out the object reference when it's called?
    Hmm, I guess. I got confused because I'm swapping between String and double values a lot. Taking in an entered number as a String and converting it to a double.
    I think I originally confused toString() with String.valueOf().
    I wouldn't have getYearlySalary() for SalariedEmployee
    and getHourlySalary() for HourlyEmployee. That
    defeats the purpose of polymorphism and dynamic
    typing. Yes, but I do have one polymorphic method --pay(). Each Employee is paid a different way. The one method we were supposed to be able to call on all Employees is just pay(). There is one version of pay() for HourlyEmployees that uses gethourly_rate() and gethours_worked() to get hourly rate and hours worked. The other version of pay() in SalariedEmployees takes in their yearly salary and number of pay periods worked.
    Better to have a getSalary() method in your
    Employee interface and let each subclass implement it
    the way they want to. SalariedEmployee will return
    their yearly salary, HourlyEmployee will return
    hourlySalary*hoursWorkedOK, that's one idea.
    But darnit, I would still like to know how to get my original design to work. So I should change returnBasicInfo() to toString(), you think?

  • Abstract method and class

    I'm a beginner in Java and just learn about abstract method and class.
    However, i am wondering what is the point of using abstract method/class?
    Because when I delete the abstract method and change the class name to public class XXXX( changed from "abstract class XXXX), my program still runs well, nothing goes different.
    Is it because I haven't encountered any situation that abstract method is necessary or ?
    Thanks!

    Yes - you probably haven't encountered a situation where you need an abstract.
    Abstract classes are not designed to do anything on their own. They are designed to provide a template for other classes to extend by inheritance. What you have build sounds like a concrete class - one which you are creating instances of. Abstract classes are not designed to be ever instantiated in their pure form - they act like a partial building block, which you will complete in a class which extends the abstract.
    An example might be a button class, which provides some core functionality (like rollover, rollout etc) but has an empty action method which has to be overwritten by a relevant subclass like 'StartButton'. In general, abstract classes may not be the right answer, and many people would argue that it is better to use an interface, which can be implemented instead of extended, meaning that you can ADD instead of REPLACING.
    Not sure if that helps.. there are whole chapters in books on this kind of thing, so it's hard to explain in a couple of paragraphs. Do some google searches to find out more about how they work.

  • Using an abstract method to assign an annotion property

    Hi Guys
    I have an annotation for specifiying that a method requires a transation. It's very simple, and looks like this:
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface TransationRequired
        PersistenceUnitDescriptor persistenceUnitDescriptor();
    }PersistenceUnitDescriptor is a simple enum, and I use Aspect J to weave code around methods annotated with this annotation.
    When I annotate a method like this
    @TransationRequired(persistenceUnitDescriptor = PersistenceUnitDescriptor.XXX)
         public Boolean func(String xx)
             //TODO: Something
         }It works fine, but when I annotate like this :
    @TransationRequired(persistenceUnitDescriptor = getPersistenceUnit())
         public Boolean func(String xx)
             //TODO: Something
         }the apect code is never run.
    getPersistenceUnit() is an abstract method and it is the only thing which is different between the two cases.
    I'm not sure if this is beacuse of the annotation or because the weaving, but I thought I would ask in the annotation categroy just in case.
    Anyone got an idea as to what may be causing this?
    Thanks in advance,
    Vackar

    VackarAfzal wrote:
    OK, Thanks for the tip. Pity that it has to be constant, in my opinion annotations would be a lot more powerful if you could dynamically change attributes. That really would make them more than just an alternative to annoying config files. But perhaps there are some technical details that I'm not aware of which makes this idea seem silly.Annotations were designed as a compile-time construct so the values within need to be compile time constants. At runtime, dynamic proxies are used to construct objects whose methods will return the values in question. You are free to construct your own objects implementing the interface of an annotation type at runtime that return values determined more dynamically.

  • Why am i able to use abstract methods id they aren't yet implemented?

    For example, why i can use this [http://docs.oracle.com/javase/7/docs/api/java/nio/CharBuffer.html#slice] if this is abstract?
    Edited by: 947971 on 13-set-2012 10.38

    947971 wrote:
    Yes, but if CharBuffer has a method declared:
    public abstract CharBuffer slice()So i can't use the method slice() because it's not implemented.
    And why , indeed, i'm able to use it?Because it is implemented by the actual class being used. You can't instantiate abstract classes, so there is a subclass of CharBuffer which does implement the method.
    If you take the interface Comparable, you see that it has an (implicitly)abstract method compareTo. A class that implements Comparable is Integer, so you can easily write:
    Comparable<Integer> i = new Integer(100);
    i.compareTo(new Integer(55));

Maybe you are looking for

  • Tax Column on the Customer Line Item Report

    Hi All We need a report for AR that has the fields : Business Area, Customer, Document Type, Document Number, Clearing Document(if any), Currency, Posting date, Amount, tax amount, payment amount, due date, payment date.. I tried the standard report

  • Scheduling Problem in Productoin order

    Greetings .....                  i have on emtaerila whih has one opeartion which take 3 min for one number this opeartion is performed on a work center which available 1224 min per day .... now theroticaly ..                   1   nos               

  • "IT_SPFLI" is not an internal table "OCCURS n" specification is missing.

    I follow this tutorial. I replaced the 2  tables into sflight and spfli table. http://www.****************/Tutorials/BSP/UsingTableView/demo.htm and this error occurred. "IT_SPFLI" is not an internal table "OCCURS n" specification is missing.

  • Date format is corrupted while exporting GridView data to excel

    I have set UK culture on my machine. Date is getting exported correctly. I have written following code: Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=IncidentsSearch.xls"); Response.ContentType = "applicatio

  • First Time FIll Rate Report in BI

    Hi SAP Gurus, Has anyone ever developed First Time Fill Rate report in BI. If yes. Please share how did you do that. Thanks and Regards