Abstract classes and OO theory...

I have an OO theory question related to abstract classes and their member variables. I realize opinions will vary from person to person but I'll ask anyway...
If I'm creating an abstract class, should member variables that will be used by subclasses be private or protected? Why? Either way, they will have accessor methods for classes that instantiate them (where appropriate) but I'm debating whether or not to give subclasses direct access to these variables or not.
To me, it seems odd to make variables in the abstract class private but I'm curious what your opinions are.
Thanks...

I knew you'd say that. I'd like to play along with a for-instance, if you will allow ... here's an example parent class:
public abstract class ProvideMenu   extends JFrame {
  protected              JMenuBar       jmbar;
  protected              JMenu          jmfile,
                                        jmedit,
                                        jmhelp;
  protected              JMenuItem      jmfnew,
                                        jmfopen,
                                        jmfsave,
                                        jmfsaveas,
                                        jmfprint,
                                        jmfexit,
                                        jmecopy,
                                        jmepaste,
                                        jmhabout,
                                        jmhcontents;
  public ProvideMenu() {
    jmbar       = new JMenuBar();
    jmfile      = new JMenu( FILE_MENU );
    jmedit      = new JMenu( EDIT_MENU );
  public abstract void aMeth();
}Now the subclass does not need to provide setProvideMenuFont( new Font( ... ) ) and Font getProvideMenuFont() methods, setProvideMenuEnabled(), etc. but can use the standard methods setFont, getFont setBackground(), setEnabled, etc, etc.
Mind you I'm not advocating this ... what I am doing is trying to open the discussion up a bit - I hope no one minds ... what better design - just a for-instance - would you advocate?
~Bill

Similar Messages

  • What is the diff b/w Abstract class and an interface ?

    Hey
    I am always confused as with this issue : diff b/w Abstract class and an interface ?
    Which is more powerful in what situation.
    Regards
    Vinay

    Hi, Don't worry I am teach you
    Abstract class and Interface
    An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
    Edited by SASIKUMARA
    SIT INNOVATIONS- Chennai
    Message was edited by:
    sasikumara
    Message was edited by:
    sasikumara

  • Difference between abstract class and the normal class

    Hi...........
    can anyone tell me use of abstract class instead of normal class
    The main doubt for me is...
    1.why we are defining the abstract method in a abstract class and then implementing that in to the normal class.instead of that we can straight way create and implement the method in normal class right...../

    Class vs. interface
    Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
    For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
    With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
    This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
    Interface vs. abstract class
    Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
    Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

  • When we will go for an abstract class and when we will go for an interface?

    it's always some what confusing to choose an abstract class and an interface,can anybody post a suitable answer for this.

    jwenting wrote:
    with experience and the insight it brings, you will know which to use when.
    Without it, it can't be explained.
    More often than not there's no X OR Y anyway.It's fortunate that there are posters here who possess the insight and experience necessary to explain this. The principal differences between an abstract class and an interface are,
    1. An abstract class can carry implementation, whereas an interface cannot.
    2. An abstract class is singly inherited, wheras an interface is multiply inherited.
    So use an abstract class when the implementation it can carry outweights the fact that it cannot be multiply inherited That's the gist of it.
    The inheritance relationship where this happens is when the supertype is a general concept of which all potential subtypes are special cases. This is called a specialization (or sometimes a generalization) relationship. For example Apple and Banana are Fruit. Or Car and Bike are Vechicle. The Fruit and Vechicle supertypes are general concepts of which their subtypes are special cases. In this case make Fruit and Vechicle abstract classes because the subtypes will benefit from a shared implementation.
    If you don't have a clearcut specialization/generalization relationship make the supertype an interface. An example could be the Comparable supertype. The potential subtypes aren't supposed to be specializations of the Comparable concept, they're suppose to become Comparable (and make this property an integral part of their being). This is not a specialization/generalization relationship. Instead the supertype is intended to add character to the subtypes. The subtypes are unlikely to benefit from an inherited implementation. So make Comparable an interface.

  • When should I use abstract classes and when should I use interfaces?

    Can any body tell me in which scenario we use /we go for Interface and which scenario we go for abstract class, because as per my knowledge what ever thing we can do by using Interface that thing can also done through abstract class i mean to say that the
    behavior of the two class.
    And other thing i also want to know that which concept comes first into the programming abstract class or Interface.
    S.K Nayak

    The main differences between an abstract class and an interface:
    Abstract
    An abstract class can contain actual working code (default functionality), and can have either virtual or abstract method.
    An abstract class must be sub-classed and only the sub-classes can be instantiated. Abstract methods must be implemented in the sub-class. Virtual methods may be overridden in the sub-class (although virtual methods typically contain code, you still may
    need/want to override them). A good use for an abstract class is if you want to implement the majority of the functionality that a class will need, but individual sub-classes may need slightly different additional functioality.
    Interface
    An interface only contains the method signatures (method name and parameters), there is no code and it is not a class.
    An interface must be implemented by a class. An interface is not a class and so it cannot be sub-classed. It can only be implemented by a class. When a class implements an interface, it must have code in it for each method in the interface's definition.
    I have a blog post about interfaces:
    http://geek-goddess-bonnie.blogspot.com/2010/06/program-to-interface.html
    (sorry, I have no blog posts specific to abstract classes)
    ~~Bonnie DeWitt [C# MVP]
    http://geek-goddess-bonnie.blogspot.com

  • Abstract class and RMI

    Hi!
    I have a desgin where I have an abstract class that in its constructor registers itself in a registry and define three abstract methods. Then I have a class that extends the abstract class and implements the three methods.
    One of the methods inserts som text in a textArea defined in the child of the abstract class but when I call this method remotly I get a nullpointer exception saying that the textArea has not been initialized. The child ofcause calls super in its constructor.
    So my question is can you not extend an abstract class that register it self in the constructor and then call methods remotly that uses variables that have been initialized in a childs constructor?
    Have your any idea to why I get the nullpointer exception?
    Peter

    >
    This sounds like there might be a misunderstanding
    about the nature of methods and variables. If, for
    instance, your client looks something like this:
    RObject roo = ...// get via RMI
    TextArea text = roo.getTextArea();
    text.setText("...");
    My design is more like this:
    public interface Subscriber extends Remote {
      public void notifySubscriber();
    public abstract class A implements Subscriber {
      a() {
        server.addSubscriber(this);
      public abstract method1();
      // some more abstract methods
      public void notifySubscriber() {
        // do some stuff
        method1();
    public class B extends A {
      JTextArea text;
      A() {
        super();
        text = new JTextArea();
      public void method1() {
        // do some stuff
        // then text is null when called remotly
        text.setText("Hello");
    }Hope this makes my design more clear and you can see the problem.
    Thanks in advance

  • ABSTRACT class and method

    Dear all Abaper experts,
    I am doubt on a abap object program shown as below. It is a ABSTRACT class and method. However, during compiling, an error message is displayed "The abstract method 'WRITE_STATUS' may not be implemented". What does it mean?
    REPORT  ZOOP_ABSTRACT.
    * Class Declaration
    CLASS vehicle DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS: accelerate,
                 write_status ABSTRACT.
      PROTECTED SECTION.
        DATA speed TYPE i.
    ENDCLASS.
    CLASS plane DEFINITION INHERITING FROM vehicle.
      PUBLIC SECTION.
        METHODS: rise.
      PROTECTED SECTION.
        DATA altitude TYPE i.
    ENDCLASS.
    CLASS ship DEFINITION INHERITING FROM vehicle.
    ENDCLASS.
    * Class Implementation
    CLASS vehicle IMPLEMENTATION.
      METHOD accelerate.
        speed = speed + 1.
      ENDMETHOD.
    ENDCLASS.
    CLASS plane IMPLEMENTATION.
      METHOD rise.
        altitude = altitude + 1.
      ENDMETHOD.
      METHOD write_status.
        WRITE: / 'Plane speed:', speed.
        WRITE: / 'Altitude:', altitude.
      ENDMETHOD.
    ENDCLASS.
    CLASS ship IMPLEMENTATION.
    ENDCLASS.
    * Global Data
    DATA: plane_ref TYPE REF TO plane,
          ship_ref  TYPE REF TO ship.
    * Classical Processing Blocks
    START-OF-SELECTION.
      CREATE OBJECT: plane_ref,
                     ship_ref.
      CALL METHOD: plane_ref->accelerate,
                   plane_ref->rise,
                   plane_ref->write_status,
                   plane_ref->accelerate,
                   plane_ref->write_status.
    All answers are welcome and appreciate for the help.

    Hi,
    try this code I've rearranged your Class Implementation and just added the foll code;
      write_status REDEFINITION in the Definition part of the Subclass.
    * Class Declaration
    CLASS vehicle DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS: accelerate,
                 write_status ABSTRACT.
      PROTECTED SECTION.
        DATA speed TYPE i.
    ENDCLASS.
    * Class Implementation
    CLASS vehicle IMPLEMENTATION.
      METHOD accelerate.
        speed = speed + 1.
      ENDMETHOD.
    ENDCLASS.
    CLASS plane DEFINITION INHERITING FROM vehicle.
      PUBLIC SECTION.
        METHODS: rise,
                 write_status redefinition.   
      PROTECTED SECTION.
        DATA altitude TYPE i.
    ENDCLASS.
    CLASS plane IMPLEMENTATION.
      METHOD rise.
        altitude = altitude + 1.
      ENDMETHOD.
      METHOD write_status.
        WRITE: / 'Plane speed:', speed.
        WRITE: / 'Altitude:', altitude.
      ENDMETHOD.
    ENDCLASS.
    CLASS ship DEFINITION INHERITING FROM vehicle.
      PUBLIC SECTION.
        METHODS: write_status redefinition. 
    ENDCLASS.
    CLASS ship IMPLEMENTATION.
      METHOD write_status.
        WRITE: / 'In Ship Class.'.
      ENDMETHOD.
    ENDCLASS.
    * Global Data
    DATA: plane_ref TYPE REF TO plane,
          ship_ref  TYPE REF TO ship.
    * Classical Processing Blocks
    START-OF-SELECTION.
      CREATE OBJECT: plane_ref,
                     ship_ref.
      CALL METHOD: plane_ref->accelerate,
                   plane_ref->rise,
                   plane_ref->write_status,
                   plane_ref->accelerate,
                   plane_ref->write_status,
                   ship_ref->write_status.
    Best Regards,
    Sunil.

  • Question about abstract classes and instances

    I have just read about abstract classes and have learned that they cannot be instantiated.
    I am doing some exercises and have done a class named "Person" and an abstract class named "Animal".
    I want to create a method in "Person" that makes it possible to set more animals to Person objects.
    So I wrote this method in class Person and compiled it and did not get any errors, but will this work later when I run the main-method?
    public void addAnimal(Animal newAnimal)
         animal.add(newAnimal);
    }Is newAnimal not an instance?

    Roxxor wrote:
    Ok, but why is it necessary with constructors in abstract classes if we don�t use them (because what I have understand, constructors are used to create objects)?Constructors don't create objects. The new operator creates objects. An object's c'tor is invoked after the object has already been created. The c'tors job is to initialize the newly-created object to a valid state. Whenever a child object is created, the parent's c'tor is run before the child's c'tor, so that by the time we're inside the child's c'tor, setting up the child's state, we know that the parent (or rather the "parent part" of the object we're initializing) is in a valid state.
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Concrete classes implement abstract class and implements the interface

    I have one query..
    In java collection framework, concrete classes extend the abstract classes and implement the interface. What is the reason behind extending the class and implementing the interface when the abstract class actually claims to implement that interface?
    For example :
    Class Vector extends AbstractList and implements List ,....
    But the abstract class AbstractList implements List.. So the class Vector need not explicitly implement interface List.
    So, what is the reason behind this explicit definition...?
    If anybody knows please let me know..
    Thanx
    Rajendra.

    Why do you post this question again? You already asked this once in another thread and it has been extensively debated in that thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=347682

  • Java abstract classes and methods

    Can anyone please tell me any real time example of abstract classes and methods.
    I want to know its real use. If anyone have ever used it for some purpose while programming please do tell me.

    Ashu_Web wrote:
    No please.. I just want to know if you have used it while programming. Like "an abstract class can be used to put all the common method names in it without having to write actual implementation code."That would describe an Interface better than an abstract class. Abstract classes usually have at least some implementation.
    I want to know its usage in programming, not just a definition. I guess you understand what I am looking for.Yes, and I gave you one: java.util.AbstractList. It can be found inside the src.zip in your JDK directory and it is a pretty good example for an abstract class that provides some implementation and defines exactly what is necessary to make a full List implementation.

  • Abstract class and class

    What is the difference between abstract class and class in java?

    arcadesstuff wrote:
    Abstract class: a class that contains at least one abstract method. As has already been mentioned, abstract classes need not contain any methods at all. Have a look at the abstract class you posted; it's still abstract, though it contains no abstract methods. Note that if one declares any method of a class abstract, the class itself must be declared abstract as well.
    When you implement the abstract class Animal, you will have to write the code of those two abstract methods from above.Your example contains no abstract methods. Abstract methods must be marked with the keyword "abstract".
    ~

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

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

Maybe you are looking for

  • My lock screen keeps freezing ios 7.1

    Hi guys, I want to know if I am alone in this issue or if it is widespread? Since updating my iphone 5 to ios 7.1 my lock screen freezes. Not all the time, mainly if there is a notification of a text etc. I have to turn the phone off and on and it so

  • I am new to PS PS6 and purchased PS Classroom in a Book as a primer.  In Lesson 1 (using the 01B_Sta

    I am new to PS PS6 and purchased PS Classroom in a Book as a primer. In Lesson 1 (using the 01B_Start.psd example) I am able to type and move horizontal text but when I follow the instructions (exactly as writ!) to change the text colour, via a swatc

  • Region transpose slider missing

    Dear all - I want to transpose a loop / recorded region but the +-12 Semitone slider does not show up. I select the region, open the editor but can only see a grey field with the name of the region - no transpose slider. Can anybody help or give a hi

  • D600 raw file could not open in Aperture, but ok in Preview

    I import D600 photo to my Aperture library all photo are in RAW format, but some file (almost 1-2 out of 100) could not view in Aperture, which show "Unsupported Image Format", but which could open in Preview, I try to import those file again and I g

  • Wf-XML with Guided Procedures to start other workflows e.g BusinessWorkflow

    HI! Is it possible with Guided Procedures to create a Wf-XML file and send it to an other Workflow engine, to start a process with the parameter defined in the XML file ? This would be required to start an webflow in R/3 Business Workflow. This Webfl