Extend abstract class & implement interface, different return type methods

abstract class X
public abstract String method();
interface Y
public void method();
class Z extends X implements Y
  // Compiler error, If I don't implement both methods
  // If I implement only one method, compiler error is thrown for not
  // implementing another method
  // If I implement both the methods,duplicate method error is thrown by 
  //compiler
The same problem can occur if both methods throw different checked exceptions,or if access modifiers are different..etc
I'm preparing for SCJP, So just had this weired thought. Please let me know
if there is a way to solve this.

Nothing you can do about it except for changing the design.
Kaj

Similar Messages

  • 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
    ~

  • Question about Classes, Abstract  Classes and Interfaces.

    I have been experimenting with Classes, Abstract Classes and Interfaces and wonder if anyone can explain this to me.
    I was looking for a way to assign a value to a variable and then keep it fixed for the session and have devised this.
    First I create an abstract class like this:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public static void setServerName(String serverName) {
              ServerName = serverName;
         public static String getServerName() {
              return ServerName;
    }and then I created an interface
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }And finally the class itself with some test lines in it so I could see what was going on:
    public class CreateDatabase extends DatabaseConnection implements DatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
         public CreateDatabase(){     
              setServerName("Server Name 1");
              System.out.println ("Before update ");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("After update ");
              setServerName("Server Name 2");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("==========================");
    }The output I get from the above is:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================I also tried this in another class which calls the above class to see if I get the same effect
    public class CheckDatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
              CreateDatabase.setServerName("Server 3");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 4");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 5");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
    }The output of which is this:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1Can anyone explain why I appear to only be able to change or set the ServerName only the once?
    Is this the correct way to do it? If it is it's exactly what I am looking for, a way to set the value of variable once in a session and then prevent it being changed.
    Or is there a better way of doing this.
    What I want to use this for is for example, storing the accesses to a database on a server. I won't know what server the database will be stored on nor what the database is called so I create an INI file which stores this information in encrypted format, which is set by the database administrator. It occurs to me I can use this method to then retrieve that data once and once only from the INI file and use that throughout the life of the session to access the database.
    Any help appreciated
    Regards
    John

    Not gonna read all of it, but this jumps out:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }You have two completely separate variables (with two different names, for that matter, since you were inconsistent in your capitalization, but it wouldn't make a difference if they did have the same name with the same case). And the one in the interface is implicitly public, static, and final.
    Anytime you refer to "servername" through a reference of type DatabaseAccess, it refers to the one declared in the interface.
    Anytime you refer to "ServerName" inside the DatabaseConnection class, it refers to the one declared in that class.

  • Abstract class Vs interface

    Hi,
    I have to buid a report in ECM with complete details of the engineering as well as production. This include workflow as well as various fucntionality depends upon the criterion and user's event.
    I am implementating in OOPS and I Want to know that when I should use the Abstract class and when interface  ?
    Because as per me both serve the same purpose. Kindly send me the exact difference so that i can efficiently use the same.
    Thanks
    Prince

    When inheriting A Interface We have to inherit all the methods of the Interface there's no other option whereas with abstract classes we can inherit the members that we are in need of.
    Just the interface has to have body of the method and the method is to be used by the classes inheriting it. Whereas in the case of Abstract Class it can have declarations (Other than the abstract method) and it can be further extended in the classes inheriting the Abstract Class.
    Interface contains all abstract methods,all methods compulsory implemented by particular class, interface does not contain Constructor
    abstract classes are designed with implemantion gaps for sub-class to fill in.
    interfaces are sintacticlly similar to classes but they lack insance variables & methods.
    abstract classes can also have both abstract methods & non-abstract methods. where as in interface methods are abstract only, & variables are implicitly static&final
    regards
    Preetesh

  • Difference between Abstract Classes Vs Interface

    Hi,
    Can u pls mention all the differences between Abstract Classes and Interface.? I've mentioned the differences I've known here.
    Known Differences:
    (*) An interface cannot implement any methods, whereas an abstract class can.
    (*) A class can implement many interfaces but can have only one superclass
    Can U pls mention at what situation(practical situation) we've to go for abstract class or Interface?
    Tell me the situation when we have to go for abstract class?
    Tell me the situation when we have to go for interface?
    Please Reply me
    Thanks & Regards
    Venkatesh

    There are more differences, and one really important is that abstract classes can also define class variables, while interfaces cannot. I think the question of when to use interfaces or abstract classes is not always easy to answer, but yourself have pointed some tips you should be aware of :
    If you need that some funcionality of the class is derived by more than one "parent" then you should use interfaces, since you cannot extend more than one class.
    If your "superclass" needs to define some class variables then the choice must be made to have a superclass and then extend it. Also this is applicable if there is a method that can be programmed at a higher level (in interfaces you cannot program methods).
    But the answer to the question is still not easy. And remember, you can always mix both tipes, you can extend one class and implement some interfaces.
    Examples or that are very common in the Java API for AWT or Swing components, for example javax.swing.JLabel extends javax.swing.JComponent (that is beacuse a JLabel IS a JComponent and it uses some variables and methods programmed at the JComponent "level") and it also implements some interfaces: Accessible, ImageObserver, MenuContainer, Serializable & SwingConstants.
    I hope this helps.
    Zerjillo

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

  • Abstract Class X Interfaces

    1.The Java language has two similar concepts : Abstract Classes and Interfaces. So, When its better to use one or other technique and the advantages and disadvantages of each one ?

    Classes can implement any number of interfaces but can extend only one class. Interfaces are used when a class might want to implement that interface but extend another class. However, interfaces cannot have implementation, so that's what abstract classes are used for.

  • What is the difference between Abstract class and Interface ?

    Hi,
    Could u plz tell me the difference between Abstract class and Interface?
    Thanks in advance.
    Gopi

    Lots.
    An abstract class can contain some method implementations, or indeed all the method implementations. It may contain methods with all the various access modifiers. It cannot be instantiated. A class may inherit from only a single abstract class.
    An interface contains only public method stubs and constants. A class may implement multiple interfaces. An interface cannot (obviously) be instantiated.
    Abstract classes are particularly useful when you need to provide a semi-complete implementation for reuse. Interfaces are used more like types.
    Look at java.util.* for some good examples of the use of both.

  • Difference between abstract classes and interfaces

    I actually wonder about what are the differences between abstract classes and interfaces may somebody give an example code about it?
    and i have one more question how can i use interfaces like multiple inheritance ? i mean when i implement an interface like
    class a extends b implements c,di have to use all c and d methods but what that methods means?
    I mean as i know we cannot make implementations of methods in interfaces
    but for example in runnable interface there is a method like run() and it has been defined somewhere because it knows what to do(i mean when it will run), i just write my code into that method .

    Once you get past the starting point (I am referring to the OP here), there are a few salient differences:
    You can only extend (or generalize) a single superclass; however, you can implement (or realize) multiple interfaces. As such, all things being equal, using an interface in lieu of an abstract class 'frees' your design. Later, if you want the implementor of an interface to inherit from another class, there is not issue.
    Any abstract method specifies a contract. However, abstract classes allow you to also add common behavior to subclasses. This is an overused justification for abstract classes, IMO. You can achieve the same effect using delegation and still having interfaces.
    Always program to interfaces wherever possible. This means that you define an interface and have an implementing class (usually at a minimum). Do not do this for all your classes, but rather the ones that make your system unique (the domain model or M in MVC architecture). This allows you to later change implementation with a minimal amount of refactoring. This is a core precept from the Group of Four and any number of decent programming books.Best of luck.
    - Saish

  • Abstract class vs Interface difference

    hi guys
    As such i know the basic difference ,but i want toknow what is the differnece between a interface and an abstract class with all the abstract methods in it.
    thanks a lot
    yash

    ,but i want
    want to know what is the differnece between a
    interface and an abstract class with all the abstract
    methods in it.You can view a class and an interface as being on the opposite extreme ends on a concrete-abstract scale.
    Say you start out with a fully concrete class. Just by adding the abstract keyword the class becomes abstract. You then remove implementation from this abstract class by making more and more methods abstract and finally you also make all methods public. You now basically have an interface. You just replace abstract class with interface and there you are.
    Basically Java wouldn't have to define an interface. The compiler could recognize and mark totally abstract classes as "interfaces" internally. The rules for extension would be that you can only extend one class carrying implementation. All other classes must be totally abstract. But admittedly, the system with declared interfaces is much more convenient for the programmer. You know up front just by looking at it that this "class" must stay totally abstract.

  • Two methods with same name but different return type?

    Can I have two methods with same name but different return type in Java? I used to do this in C++ (method overloading or function overloading)
    Here is my code:
    import java.io.*;
    public class Test{
    public static void main(String ar[]){
    try{          
    //I give an invalid file name to throw IO error.
    File file = new File("c:/invalid file name becasue of spaces");
    FileWriter writer = new FileWriter(file ,true);
    writer.write("Test");
    writer.close();     
    } catch (IOException IOe){
         System.out.println("Failure");
    //call first method - displays stack trace on screen
         showerr(NPe);
    //call second method - returns stack trace as string
            String msg = showerr(NPe);
            System.out.println(msg);
    } // end of main
    public static void showerr(Exception e){
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         e.printStackTrace(pw);
         try{
         pw.close();
         sw.close();
         catch (IOException IOe){
         IOe.printStackTrace();     
         String stackTrace = sw.toString();
         System.out.println("Null Ptr\n" +  stackTrace );
    }//end of first showerr
    public static String showerr(Exception e){
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         e.printStackTrace(pw);
         try{
         pw.close();
         sw.close();
         catch (IOException IOe){
         IOe.printStackTrace();     
         return sw.toString();
    }//end of second showerr
    } // end of class
    [\code]

    Overloading is when you have multiple methods that have the same name and the same return type but take different parameters. See example
    public class Overloader {
         public String buildError(Exception e){
              java.util.Date now = new java.util.Date() ;
              java.text.DateFormat format = java.text.DateFormat.getInstance() ;
              StringBuffer buffer = new StringBuffer() ;
              buffer.append(format.format(now))
                   .append( " : " )
                   .append( e.getClass().getName() )
                   .append( " : " )
                   .append( e.getMessage() ) ;
              return buffer.toString() ;
         public String buildError(String msg){
              java.util.Date now = new java.util.Date() ;
              java.text.DateFormat format = java.text.DateFormat.getInstance() ;
              StringBuffer buffer = new StringBuffer() ;
              buffer.append(format.format(now))
                   .append( " : " )
                   .append( msg ) ;
              return buffer.toString() ;
         public String buildErrors(int errCount){
              java.util.Date now = new java.util.Date() ;
              java.text.DateFormat format = java.text.DateFormat.getInstance() ;
              StringBuffer buffer = new StringBuffer() ;
              buffer.append(format.format(now))
                   .append( " : " )
                   .append( "There have been " )
                   .append( errCount )
                   .append( " errors encountered.")  ;
              return buffer.toString() ;
    }Make sense ???
    Regards,

  • Abstract class and interface????

    hi all, i would like to know the difference between abstract class and interface....could anybody enlighten me on this....

    Like the others have mentioned you can implement more than one interface, but only inherit from one abstract class. An abstract class can provide some implementation.
    steve http:\\www.jamonapi.com

  • Abstract class Vs  Interface and importance of using

    Hi All,
    I want to know what is the difference between Abstract class and Interface.
    and what is the importance of using them.
    Moderator message: please search for available information/documentation.
    Edited by: Thomas Zloch on Sep 27, 2011 1:55 PM

    Please refer to this thread, already this is discussed in forums
    [ABAP Objects.. Abastract & Interface Class;
    Thanks
    Pavan

  • Internal class implementing interface extending abstract interface :P

    Confused ha? Yeah me too. RIght here it goes.
    Theres an abstract interface (abstractIFace) that has for example method1() method2() and method3(). There are two other interfaces iFace1 and iFace2 that extend abstractIFace. Still with me? :P iFace1 only uses method2() whereas iFace2 uses method1(), method2() and method3(). Internal classes implementing these are then used. The reason is so that when returning an object one method can be used that will return different types of objects. But this doesnt work. It says that all the classes in the abstractIFace must be used/implemented but I only want method2() in iFace1 and all in iFace2.
    Just say what the f*ck if this is too confusing cos i think it is and i did a crap job explaining!! :P

    public interface IFace {
        void method1();
        void method2();
        void method3();
    public class Test {
        private static class Class1 implements IFace {
            public void method1() {
                System.out.println("method1");
            public void method2() {
                System.out.println("method2");
            public void method3() {
                System.out.println("method3");
        private static class Class2 implements IFace {
            public void method1() {
                throw new UnsupportedOperationException();
            public void method2() {
                System.out.println("method2");
            public void method3() {
                throw new UnsupportedOperationException();
        public static IFace createObject(boolean flag) {
            return flag ? (IFace) new Class1() : new Class2();
    }

  • Interfaces having methods of same signature but different return types

    I have two interfaces in two files:
    public interface InterfaceA
    int f();
    public interface InterfaceB
    void f();
    Now I want to write a class that implements these two interfaces. Is it possible? If yes, could you please provide a code example?

    The easiest thing would be to change one of the names! Another approach is to have views of the class implement one or both interfaces.
    Both:
    class C {
        private InterfaceA a = new InterfaceA() {
            public int f() {
                return 0;
        public InterfaceA asA() {
            return a;
        private InterfaceB b = new InterfaceB() {
            public void f() {
        public InterfaceB asB() {
            return b;
    }One:
    class B implements InterfaceB {
        private InterfaceA a = new InterfaceA() {
            public int f() {
                return 0;
        public InterfaceA asA() {
            return a;
        public void f() {
    }

Maybe you are looking for

  • Adding an event to your iCal on your iPod touch

    So...I understand you can sync the iPod touch's iCal with a calendar on your main computer (using Entourage, outlook, or simply iCal.) BUT....can you add events directly into your Ipod touch...and then simply view both calendars at the same time like

  • Is there a way to see the effects

    Hi guys, I think in FCE4, we cannot see the effects being applied unless we drag the effects onto the clip & test it out. I bought the Tom Wolsky book & inside the book comes with a CD that shows all the transition. I was wondering if there is a simi

  • Transportation of security through header from proxy to business service

    Hi, I have an application in which i have implemented web security at proxy service level. I couldnt transport that to business service. I have embedded USERNAME and PASSWORD in the header of the proxy service. This authentication should pass through

  • Error message 0xc000001d in Photoshop CS5 Trial

    I have installed the Photoshop CS5 Trial, and when I tried to initiate the program, I got a error message 0xc000001d. Do you have any idea, if this failure occurs due my operating system use a athlon XP processor 2.4GHz? Are there any solution for th

  • Spotlight comments disappeared

    I have a folder containing close to 300 aliases to other files in another folder. I added "Spotlight Comments" to most of them. Everything seemed to work for a long time. Recently, I cut and paste some long description text to the comment field in th