Implements versus Extends

I'm an inexperienced programmer.
After reading a number of articles I've been convinced that its generally better to use interfaces and implements, as opposed to classes and extended subclasses. However, I'm not sure how I should do that given my current situation?
I have a base class with a number of functions and variables. There is one function that I need to implement differently for a number of situations. At the moment I have something like...
class base {
int a;
int b;
void functionA() { does whatever; }
void functionB() { does whatever; }
class baseA extends base {
void functionC() { does whatever; }
class baseB extends base {
void functionC() { does whatever; }
class baseZ extends base {
void functionC() { does whatever; }
If I use implements instead of extends, doesn't that mean I have to include a copy of functionA and functionB in all of those subclasses? Isn't that inconvenient? Or is there a better way of doing this?
Thanks for any help!

I'm an inexperienced programmer.
After reading a number of articles I've been convinced
that its generally better to use interfaces and
implements, as opposed to classes and extended
subclasses. However, I'm not sure how I should do
that given my current situation?
I have a base class with a number of functions and
variables. There is one function that I need to
implement differently for a number of situations. At
the moment I have something like...
class base {
int a;
int b;
void functionA() { does whatever; }
void functionB() { does whatever; }
class baseA extends base {
void functionC() { does whatever; }
class baseB extends base {
void functionC() { does whatever; }
class baseZ extends base {
void functionC() { does whatever; }
If I use implements instead of extends, doesn't that
mean I have to include a copy of functionA and
functionB in all of those subclasses? Isn't that
inconvenient? Or is there a better way of doing this?
Thanks for any help!Intefaces aren't always the better choice, and I would say that the situation you descibe is one of those cases where they aren't the better choice.

Similar Messages

  • Difference between implements and extends

    Hi all,
    what is the difference between implements and extends. i am sorry to ask this silly question, but i am new to JAVA.
    Thanks
    Balaji

    when you extend a class, your class that you are coding inherits every method and field from the extending class. For example:
    public class CustomFrame extends JFrame {
    //Your class's methods will be in here, but so will all of JFrame's methods.
    }You can override (most) methods from extended classes if you want them to do different things than they normally do. The most commonly overriden methods when using swing are stuff like paint(Graphics g). It needs to be overriden to repaint all of the components.
    When you imlpement something, you have to specify an interface. Interfaces have methods in them with no code. If you implement an interface, all methods in in must be defined. If not, the code will not compile. Some interfaces like ActionListener extend other classes to perform stuff. The actionPerformed(ActionEvent e) method will perform an action when a button is pressed, etc.

  • Difference between Implement and Extend

    what is the difference between implements and extends and why do we use them
    thanks,

    classes extend one other class and implement as many
    interfaces as they wish.
    interfaces extend as many interfaces as they wish.But for all that, they both just mean "inherits."
    There wouldn't even have to be two different words, since you never have a choice between X extends Y and X implements Y. For a given X and Y, only one of the two will be legal.

  • Implementing and Extends

    What is the difference between implements and extends?
    For example, public class Banner extends Applet implements Runnable =>
    If you extend a Class, then you can use the members of the superclass(which is Applet in this situation). And if you implement a Class then you can also use the members of the class. And as far as i know the Class youre implementing is called an interface. I know that an interface is not implemented yet, and it contains a lot of empty methods like public interface Series{ int getNext();  void reset();  void setStart(int x); }   .
    Then if you want to implement this interface you must use another class. In this class you define the methods and also write a couple of variables, whom you will be putting in the not implemented methods, like this=>
    class ByTwos(extends superclass) implements Series {  int start;    int val;   ByTwos(){start=0; val=0;}
    public in getNext(){val +- 2}    public void reset(){start=0; val=0;}  
    public void setStart(int x) {start=x; val=x;}        }.
    Then you create another Class with a main method and an object of type ByTwos, wherein you USE THE MEMBERS OF THE INTERFACE CLASS.
    Are the things i wrote right? What is the difference then?

    Shelby wrote:
    jverd wrote:
    If all the methods defining a type are abstract, you can make the type an interface. An
    interface is very much like a class with all abstract methods. Users of that interface
    don't care which implmentation they get. All they need to know is that they'll be able to
    call the declared methods.Dense people really annoy me, and right now I'm being REALLY dense about the advantage of using
    an interface. I can understand what you say about using an interface to define a type of something
    like an animal. But since all of the variables in an interface are final, and all of the methods are only
    signatures, it seems to me it would just be easier to create classes that use their own methods that
    actually perform a task.You're only thinking of writing the concrete classes. Think about the code that uses the type.
    Animal animal = goGetSomeRandomAnimalFromSomewhere();
    animal.speak();
    animal.feed();I define the Animal type, as an interface, and every user of Animal knows that any Animal (meaning an instance of any class that implements Animal) will be able to speak(), feed(), etc.
    Now I'm making some kind of game with animals wandering around in it. I want to draw some random animal on the screen, have it make its noise and then go eat. At the point where my code is doing that (above), I don't know what specific Animal implementation I'll get, only that it will be an Animal. So I have to declare the animal variable as a supertype of all the classes that could come back.
    The Animal type serves that purpose. It could be an abstract class, rather than an interface, but an abstract class can carry implementation, and my Animal class has no implementation. How does an Animal speak()? How does it feed()? Animal is simply a pure type. Interfaces are better suited for pure type defintions than abstract classes. That's their purpose.
    In addition, my implementing classes can implement other interfaces besides Animal, such as, for instance, Serializable or Comparable. Java doesn't support multiple inheritance of implementation, but it does support multiple inheritance of type--via being able to implement multiple interfaces.
    Remember--inheritance is primarily about type, NOT about code sharing.
    As another example, consider the java.util.List interface. You can add() to a list, remove() from it, see if it contains() a particular element, etc. There are multiple ways you could implement a List, and there's not really any common implementation you'd want to assume. So we define a List interface--the pure type--and then we implement it in very different ways via ArrayList and LinkedList. (Actually, there's a layer or two of abstract classes between List and those implementations. The abstract classes define implementations of some of the methods that do have reasonable defaults--for instance if they only rely on other methods in the List interface.)
    Now I want to do something with a List--say shuffle it or sort it or display its contents in a GUI--I don't care what kind of List you give me. I'm just going to use the methods that all lists provide to perform my operation.
    public void sort(List list) {
      // I can sort ANY List here
    }Now, if you still don't think this makes sense, can you tell me how you'd do this without interfaces?

  • Implements or extends first

    I have an object B extends A and implements Comparable
    what should I write in the class declaration
    Public class B extends A implements Comparable<B>
    or Public class B implements A extends Comparable<B>
    Thanks very much

    And I told you. Use the compiler. If you got an error message then what you tried was incorrect.
    If however there is something you don't understand then try explaining what you typed in, what the compiler error message was and ask a specific question. Not just a vague "please help".

  • Whats the difference between implements and extends!??

    Can an interface be extended or not??
    If it can whats the difference between implements and extends??
    Thank you!

    Code Sample:
    interface a implements aa{This is illegal. An interface cannot implement another interface. It can only extend another interface.
    interface a extends aa{That's the way to do it. As already said above:
    An interface can only extend another interface.
    A class can extend another class.
    A class can implement zero or more interfaces.
    So, "implements" is only used for classes that implement interfaces. For the rest, "extends" is used.

  • Streatch Moniter versus extended desktop

    Is there any kind of app that will manage your two displays to set them up in a "Streatch display" setting versus an extended desktop setting? Thanks!

    The iSight iMacs had a mini-VGA connector, so you can search the Apple Store for the "Apple VGA Display Adapter" which is $19. I understand that it is pretty short, so you will likely need a VGA extension cable that you can get locally at Best Buy.
    I would post a link, but the Apple Store links time out and would be of no use. Sorry.

  • 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();
    }

  • Implements and Extends?

    I had a question about interfaces. I know how they work but I dont see the point in having them...?
    If I put methods into an Interface, then each method in the interface must appear in that class.
    abstract interface Drive {
    public void start();
    public void accel();
    public void decel();
    public void dropTop();
    public class Car implements Drive {
    }and if I have a class that extends Car, then it also implements Drive. but I dont see the benefit of having Drive at all.
    help?

    interfaces are useful when it comes to multiple inheritance, since you can't extends more than one class, but you can implement as much interface as you want
    imagine for example that your "Car" class is supposed to extends "Vehicle", but it also has to be an Observer (for the Observable/Observer pattern)
    you can make it both a Vehicle and an Observer using:
    class Car extends Vehicle implements Observer {}and if you want your car to be a vehicle, an observer, and an oil consumer:
    class Car extends Vehicle implements Observer, OilConsumer {}if you only had two classes OilConsumer and Vehicle, you would have to choose which one car will extend ; with interfaces, you can use both at one time
    interfaces can also be used as simple markers
    did you try to search a bit before asking your question here?

  • Ok, easy question...About implements and extends

    Im sure this will be simple to all of you, but I am still new to the Java language. I want to know the difference between using "extends" and "implements" in the way that its used in these examples:
    With the "extends" keyword...
    class PrimeThread extends Thread {
             long minPrime;
             PrimeThread(long minPrime) {
                 this.minPrime = minPrime;
             public void run() {
                 // compute primes larger than minPrime
         }And then with the "implements" keyword...
    Using the interface "Runnable"
    class PrimeRun implements Runnable {
             long minPrime;
             PrimeRun(long minPrime) {
                 this.minPrime = minPrime;
             public void run() {
                 // compute primes larger than minPrime
         }Can someone please explain when you would want to use the "extends" version and when you would want to use the "implements" version? Sorry for practically insulting your intelligence...I'm just trying to learn this language without a book as an experiment to see (how much/how fast) I can learn purely using the web resources...Thanks to anyone who wishes to explain this to me.

    That's pretty much it.
    An interface may extend zero or more other interfaces.
    A class (except Object) always extends exactly one other class--either the class explicitly named with "extends", or Object if "extends" is not present.
    A class may implement zero or more interfaces.
    "Extends" implies a parent-child relationship. Interfaces extend other interfaces, and classes extend other classes.
    "Implements" implies a contract stating that the class will provide implementations for all the methods declared in the interface (or the class will be declared abstract). If a class implements A, and A extends B, then that class must implement all methods declared in A and all methods declared in B.
    Does this help?

  • Adapters-shoud i still use "implements or extends" keyword

    hi all...especially Mr. Glen McCluskey...
    i've just read the TechTips using Adapters-9 May 2000...
    there was an example about using adapters...there wasn't keyword "extends or implements" in that example ...
    so the question is:
    if i use adapters, should i still extend or implements my derived class from base class? or this formula is just enough, for example:
    frame.addWindowListener(new WindowAdapter(){................});
    the example available at: developer.java.sun.com/developer/TechTips/index.html the date is 9 May 2000 writer:Glen McCluskey ...
    thank you, all...

    I don't understand why you say "there wasn't keyword "extends or implements" in that example ", I read the article and see:abstract class A_ADAPTER implements A {
            public void f1() {}
            public void f2() {}
            public void f3() {}
            public void f4() {}
            public void f5() {}
        } which clearly implements interface A, and the class that uses this adapter must extend the adapter. So yes, your adapter must implement the interface it is adapting, and the class that is using this adapter must extend the adapter to "use" it.
    Lee

  • Instantiating a class using new with implements or extends

    I have created a class as follows:
    class MyFileFilter extends javax.swing.filechooser.FileFilter implements java.io.FilenameFilter {     
         ...code here...
    }and it all works fine. If I try to use this code directly without importing the class, I would normally use the new keyword, but since this uses extends and implements, it is giving me errors such as:
    [javac] ';' expected
    Is there any way that I can use this with the new keyword, such as:
    MyFileFilter theFilter = new MyFileFilter extends javax.swing.filechooser.FileFilter implements java.io.FilenameFilter {
         ...code here...

    maybe your ';' error is really a coding error. Here is a sample of code where I do something similar in the middle of a method.
        public static void redirectOutput() {
            try {
                // make a print stream that logs the time for each entry.
                class TimeStampPrintStream
                    extends PrintStream {
                    public TimeStampPrintStream(OutputStream out, boolean b) {
                        super(out, b);
                    public void println(String s) {
                        super.println(new Date() + ": " + s);
                System.out.close();
                System.err.close();
                System.setErr(new TimeStampPrintStream(new FileOutputStream(com.perigee.fileio.LogFile.getLogDirectory() + "System.err"), true));
                System.setOut(new TimeStampPrintStream(new FileOutputStream(com.perigee.fileio.LogFile.getLogDirectory() + "System.out"), true));
                System.err.println("System.err File");
                    System.out.println("System.out File");
            } catch (Exception e) {
                System.out.println("Could not redirect System.out/err");
                e.printStackTrace();
        }

  • Extending and implementing

    Is there a way to tell the compiler: this variable is of this class and implements that interface.
    Say for instance a Component that implements ActionListener
    extending component with an abstract class that implements ActionListener and then extend this class wouldn't work since then i can'T as well extend button textArea ect.

    if(variable instanceof Component) {
    //do something
    if(variable instanceof ActionListener) {
    //do something else
    if( (variable instanceof Component) &&
    (variable instanceof ActionListener) ) {
    // really do something else
    }

  • SRM: Extended Classic scenario: Request your help.

    Hi Guru's,
    We are implementing the EXTENDED CLASSIC SCENARIO in our project. kindly request your help.
    in our project the SRM box is :  G3OSBSR102.
    R/3 backend Box is :   RCHSBR3142.
    Now when i create a shopping cart it should create the Purchase order In SRM( G3OSBSR102) and also copy the created purcahse order in teh backend system : RCHSBR3142.
    The issue here is which Logical system should be populated in the field at item level when creating the shopping cart :BE_LOG_SYSTEM.
    1) In this field: BE_LOG_SYSTEM.
    If i populate the SRM local: G3OSBSR102., then it will consider the Business object type as : BUS2201and creates the local Po but while transfering this local created document(PO) to R/3 system is loosing the Logical system at the item level of the PO.
    If i populate this field at the item level via DEBUGG mode then system is sucessfull in transferring the document to R/3.
    2)  In this field: BE_LOG_SYSTEM.
    If i populate the SRM local: RCHSBR3142, then it will consider the Business object type as : BUS2012 and creates the purchase order in R/3 system and will not create teh local purchase order.
    Kindly request your help for any further settings if i did miss.Appreciate your help in this regards.
    Many Thanks,
    Prasad NN.

    Dear Prasad,
    To work on Extended Classic Scenario, you just have to maintain the following configuration in SPRO:
    >SAP Supplier Relationship Management
    >SRM Server
      >Cross-Application Basic Settings
       >Activate Extended Classic Scenario
    Check the flag "Extended Classic Scenario Active".
    You dont have to manipulate "BE_LOG_SYSTEM" field to choose your scenario.
    Regards
    Thiago Salvador

  • SR_ Extended Classic Scenario : Request your help please

    Hi Guru's,
    We are implementing the EXTENDED CLASSIC SCENARIO in our project. kindly request your help.
    in our project the SRM box is : G3OSBSR102.
    R/3 backend Box is : RCHSBR3142.
    Now when i create a shopping cart it should create the Purchase order In SRM( G3OSBSR102) and also copy the created purcahse order in teh backend system : RCHSBR3142.
    The issue here is which Logical system should be populated in the field at item level when creating the shopping cart :BE_LOG_SYSTEM.
    1) In this field: BE_LOG_SYSTEM.
    If i populate the SRM local: G3OSBSR102., then it will consider the Business object type as : BUS2201and creates the local Po but while transfering this local created document(PO) to R/3 system is loosing the Logical system at the item level of the PO.
    If i populate this field at the item level via DEBUGG mode then system is sucessfull in transferring the document to R/3.
    2) In this field: BE_LOG_SYSTEM.
    If i populate the SRM local: RCHSBR3142, then it will consider the Business object type as : BUS2012 and creates the purchase order in R/3 system and will not create teh local purchase order.
    Kindly request your help for any further settings if i did miss.Appreciate your help in this regards.
    Many Thanks,
    Prasad NN.

    Hi ,
    Go to SPRO
    There is a node - Activate Extended Classic scenario
    Do the config.
    Regards
    G.Ganesh Kumar

Maybe you are looking for

  • Real  time issues

    hi there, can any one share some of the issues that have been dealt with in real time. i.e.during blue print stage, <b>especially in realisation stage</b>, final preparation stage puhlease answer this question immediately

  • Designer and Developer 6.0 on PO 8i

    Hello everybody, Does anybody know if Designer and Developer 6.0 work correctly on Personal Oracle 8i? Thanks in advance, Renato

  • Not enough memory for iMac

    I purchased an iMac sometime in 2009. Within the past two years, it was used at most about 20 times.  Most of the time is is turned completely off & not even plugged in.  Basically, it has hardly ever been used.  It just turned it on again today & tr

  • Original IPhone question

    Does the original iphone not send picture mail.

  • Clear 'mocha ae cs6' from my 'open with' menu

    This is really frustrating because firstly, I have never had AE CS6 on my computer I don't know how that got there. It has been there since the day I got it from the store and the more I look at it the more it ****** me off, pardon my language. Does