Abstract class needs to be observed

Hi! Thank you for reading my post!
I have been programming seriously in Java for two years now. But sometimes I still feel like I am a rookie.
Here is the situation:
Class A is a parent class. Subclasses B, C, and D extend A. Superclass A extends Observable, and thus it needs to notify its observers when it has changed. Superclass A has an abstract method, which is implemented by subclasses B, C, and D.
Question:
When the abstract method is invoked in subclasses B, C or D, can I somehow set Superclass A as 'changed' and 'notifyObservers' without having to make the 'changed' and 'notifyObservers' call in each of the subclasses B, C and D? In others words, is there a way to implement a non-abstract method (i.e. setChanged() or notifyObservers() ) inside of an abstract method (i.e. method() as shown below )?
Reasoning:
The reason that I want to avoid having to put this code into every subclass is because the subclasses may be created in the future without the programmer knowing that the subclass needs to notify of the change/update. I want to 'dummify' the programming for the future user. In addition, there are a lot of subclasses.
Here is some code to help:
Class A extends Observable
  public void abstract method();
Class B extends A
  public void method()
    //do something here...
    //I want to avoid having to type these lines in every class
    //that extends Class A:
    setChanged();    // <-- can I avoid putting this here?
    notifyObservers();  // <-- can I put it in Class A's abstract method somehow?
Class C extends A
  public void method()
    //do something here...
    //I want to avoid having to type these lines in every class
    //that extends Class A:
    setChanged();    // <-- can I avoid putting this here?
    notifyObservers();  // <-- can I put it in Class A's abstract method somehow?
Class D extends A
  public void method()
    //do something here...
    //I want to avoid having to type these lines in every class
    //that extends Class A:
    setChanged();    // <-- can I avoid putting this here?
    notifyObservers();  // <-- can I put it in Class A's abstract method somehow?
}Thanks for any suggestions you might have!
Regards,
Julia

OK. HMMM. Maybe I figured this out. Will this work?
(Sometimes I really feel like a rookie! ;) )
Class A extends Observable
  public void method()
    this.method2()
    this.setChanged();
    this.notifyObservers();
  public void abstract method2();
Class B extends A
  public void method2()
    //do something here ....
Class C extends A
  public void method2()
    //do something here ....
Class D extends A
  public void method2()
    //do something here ....
}Ok - well, thanks anyways. I think this will work. Now I really feel stupid for even bothering to post. Oh well.
Hope you have a great day!
Thanks!
Julia

Similar Messages

  • Abstract classes: Why do they need constructors?

    As we cannot instantiate an abstract class. Why does an abstract class need a constructor?.can anyone please help me out..Thnq in advance
    OBELISK

    import java.util.*;
    import static java.lang.System.out;
    interface LineItem{
        public int getCost();
    abstract class AbstractLineItem implements LineItem{
      protected String name;
      AbstractLineItem(String name){
         this.name = name;
      public String toString(){
        return this.name+" "+getCost();
      public abstract int getCost();
    class ProductItem extends AbstractLineItem{
       private int quantity, peritem;
       ProductItem(String name, int quantity, int peritem){
         super(quantity+" "+name);
         this.quantity = quantity;
         this.peritem = peritem;
       public int getCost(){
         return this.quantity*this.peritem;
    class FlatFeeItem extends AbstractLineItem{
       private int fee;
       FlatFeeItem(String name, int fee){
         super(name);
         this.fee = fee;
       public int getCost(){
         return this.fee;
    public class Test{
      public static void main(String ... args){
        List<LineItem> items = new ArrayList<LineItem>();
        items.add(new ProductItem("Banana",6,1));
        items.add(new FlatFeeItem("Some boring thing or another",35));
        items.add(new ProductItem("Kiwi",3,3));
        for(LineItem item : items)
          out.println(item);
    }

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

  • I really need abstract static methods in abstract class

    Hello all.. I have a problem,
    I seem to really need abstract static methods.. but they are not supported.. but I think the JVM should implement them.. i just need them!
    Or can someone else explain me how to do this without abstract static methods:
    abstract class A {
    abstract static Y getY();
    static X getX() {
        // this methods uses getY, for example:
        y=getY();
       return new X(y); // or whatever
    class B extends A {
    static Y getY() { return YofB; }
    class C extends A {
    static Y getY() { return YofC; }
    // code that actually uses the classes above:
    // these are static calls
    B.getX();
    A.getX();I know this wont compile. How should i do it to implement the same?

    Damn i posted this in the wrong thread.. anyways.
    Yes offcourse i understand abstract and static
    But i have a problem where the only solution is to use them both.
    I think it is theoretically possible ot implement a JVM with support for abstract static methods.
    In fact it is a design decision to not support abstract static methods.. thats why i am asking this question.. how could you implemented this otherwise?
    There is an ugly soluition i think: using Aspect Oriented Programming with for example AspectJ.. but that solution is really ugly. So anyone has an OO solution?

  • Abstract class or inteface

    Pls give me some practical example of choosing among abstract class and interface.

    An interface is a definition of what a class should look like from the outside: use it for defining a type of class that will have multiple implementations. For instance in the 'Observer ' pattern any class implementing the observer interface can be attached to the subject. In this way when implementing the subject there is no need to know how the observers will be implemented.
    An abstract class is typically used to implement some code that is common amongst all derived classes. Coming back to the observer pattern. A abstract class BaseSubject could have some code for storing observers that have to be attached. In this way the code get's recycled and double code is prevented.
    It is very common to combine an interface with some abstract implementation. For instance when an interface has methods for attaching observers and a run method that should do 'something'. The abstract base class for all implementation could implement the attach/detach observer stuff and publish a protected method notifyObservers. An the actual classes extending this class need only fill in the run method.
    Hope this helps!

  • Abstract classes & interfaces

    In the API we have an interface namely:Set
    which is implemented by an abstract class AbstractSet.
    Class HashSet extends AbstractSet implements Set.
    Now What is need for HashSet class to implement a Set interface when it is already extending from AbstractSet class that inturn implements Set interface.

    This is probably an case of the folks at Sun refactoring their code and just missing one cleanup detail. The initial implementation of HashSet probably did not have a subclass. Then when they started to implement TreeSet, they realized that there was common functionality that they could reuse.
    As the previous writer mentioned and you observed, there is no advantage or reason for HashSet to implement Set, it's probably just a harmless oversight.

  • Abstract class with set and get methods

    hi
    how to write set and get methods(plain methods) in an abstartc class
    ex: setUsername(String)
    String getUsername()
    and one class is extending this abstract class and same methods existing in that sub class also..... how to write......plz provide some ideas
    am new to programming....
    asap
    thnx in advance

    yes... as i told u.... i am new to coding......
    and my problem is ..... i have 2 classes one is abstract class without abstract methods.. and another class is extending abstract class.....
    in abstract class i have 2 methods...one is setusername(string) and getusername() ..... how to write these two methods.... in abstract class i have private variables username...... when user logins ..... i need to catch the user name and i need to validate with my oracle database and i need to identify the role of that user and based on role of that user i need to direct him to appropriate jsp page.......
    for that now i am writing business process classes..... the above mentioned two classes are from business process.....
    could u help me now
    thnx in advance

  • Calling a super.ssuper.method but your super is a abstract class.

    Dear guys,
    Is that possible to invoke your super's super's method but your super is a abstract class?
    like:
    class GO {   public void draw() { } }
    abstract class GORunner extends GO {}
    class GOCounter extends GORunner {
    public void draw() {
    super.super.draw();
    I want to do this because I would like to take advantages of the abstract as an layer to achieve some polymorphism programming Therefore, in the later stage of the programming some code may only refer to GORunner but actually it is holding a GOCounter object.
    Thank!!

    BTW you don't need to write this
    public void draw() {
       super.draw();
    }It works but its basically the same as not having it at all.

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • EJB question: How to use abstract class in writing a session bean?

    I had written an abstract class which implements the session bean as follow:
    public abstract class LoggingSessionBean implements SessionBean {
    protected SessionContext ctx;
    protected abstract Object editRecord(Object obj) throws Exception;
    public LoggingSessionBean()
    super();
    private final String getBeforeUpdateImage(Object obj) throws Exception {
    // implement the details of extracting the backup image ...
    public void setSessionContext(SessionContext ctx)
    this.ctx = ctx;
    private final void writeThisImageToDatabase(String aStr) {
    // connect to database to write the record ...
    public final Object update(final Object obj) {
    try {
    final String aStr = getBeforeUpdateImage(obj);
    writeThisImageToDatabase(aStr);
    editRecord(obj);
    } catch (Exception e) {
    ctx.setRollbackOnly();
    This abstract class is to write the backup image to the database so that other session beans extending it only need to implement the details in editRecord(Object Obj) and they do not need to take care of the operation of making the backup image.
    However, some several questions for me are:
    1. If I write a class ScheduleSessionBean extending the above abstract class and the according 2 interfaces ScheduleSession and ScheduleSessionHome for this session bean (void update(Object obj); defined in ScheduleSession), do I still need to write the interfaces for LoggingSession and LoggingSessionHome?
    2. If I wrote the interface LoggingSession extending EJBObject where it defined the abstract methods "void update(Object obj);" and "void setSessionContext(SessionContext ctx);", that this meant I needed to write the ScheduleSession to implement the Logging Session?
    3. I used OC4J 9.0.4. How can I define the ejb-jar.xml in this case?

    Hi Maggie,
    1. do I still need to write
    the interfaces for LoggingSession and
    LoggingSessionHome?"LoggingSessionBean" can't be a session bean, because it's an abstract class. Therefore there's no point in thinking about the 'home' and 'remote' interfaces.
    2. this
    meant I needed to write the ScheduleSession to
    implement the Logging Session?Again, not really a question worth considering, since "LoggingSessionBean" can't be an EJB.
    3. I used OC4J 9.0.4. How can I define the
    ejb-jar.xml in this case?Same as you define it for any version of OC4J and for any EJB container, for that matter, since the "ejb-jar.xml" file is defined by the EJB specification.
    Let me suggest that you create a "Logging" class as a regular java class, and give your "ScheduleSessionBean" a member that is an instance of the "Logging" class.
    Alternatively, the "ScheduleSessionBean" can extend the "Logging" class and implement the "SessionBean" interface.
    Good Luck,
    Avi.

  • ".. is an abstract class.  It can't be instantiated"

    Does anyone have an idea of how I can get rid of the above error message? Here is a bit of my code:
    import java.io.*;
    import java.util.Vector;
    class Project3 {
    private BiTree company = new BiTree();
    public static void main(String[] args) throws IOException {
    Project3 run = new Project3();
    run.Command();
    public void Command() throws IOException {}
    public interface comparable {
    //not sure if need this in this class, or at all
    public int compare(Object object1,Object object2);
    public void add() {
    Employee newOne = new Employee();
    System.out.println("Enter name");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    String name = stdin.readLine();
    System.out.println("Enter title");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    String title = stdin.readLine();
    System.out.println("Enter payrate");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    payrate = Double.parseDouble.stdin.readLine();
    newOne.setTitle(title);
    newOne.setName(name);
    newOne.setPayrate(payrate);
    company.insert(newOne);
    }

    It is not possible to create instances of an abstract class.
    I hope this example helps,
    abstract class Vehicle
    public static void main(String arg[])
    Vehicle a;
    a = new Automobile(); // ok, since Automobile is a kind of Vehicle
    // The class Automobile, a special case of Vehicle
    class Automobile extends Vehicle

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

  • A Singleton variable in an Abstract Class

    Hello there people
    I have a quick question. I have made an abstract class in which I want to put an identifier (ID) int to be incremented whenever I make any of the concrete class instances that extend this abstract class.
    whould that declairation be as follows?:
    public static int IDAdditionally, I have a quick question about abstract constructors. If constructors are defined in the concrete classes, are their declairations needed in the abstract class?
    and finally, if I wanted to use the int ID (as mentioned above) then would I have to use constructor from the abstract class?
    thanks in advance for the help

    I think the OP would want a constructor in the abstract class to update that variable. Otherwise, he'd have to remember to update it in the constructor for all concrete classes. But, you don't declare constructors for the concrete class in the abstract class. You only declare constructors for the abstract class in the abstract class.

  • "Abstract" method in a non-abstract class

    Hi all.
    I have a class "SuperClass" from which other class are extended...
    I'd like to "force" some methods (method1(), method2, ...) to be implemented in the inherited classes.
    I know I can accomplish this just implementing the superclass method body in order to throw an exception when it's directly called:
    void method1(){
    throw new UnsupportedOperationException();
    }...but I was wondering if there's another (better) way...
    It's like I would like to declare some abstract methods in a non-abstract class...
    Any ideas?

    The superclass just models the information held by
    the subclasses.
    The information is taken from the database, by
    accessing the proper table (one for each subclass).??
    What do you mean by "models the information"?
    You should use inheritance (of implementation) only when the class satisfies the following criteria:
    1) "Is a special kind of," not "is a role played by a";
    2) Never needs to transmute to be an object in some other class;
    3) Extends rather than overrides or nullifies superclass;
    4) Does not subclass what is merely a utility class (useful functionality you'd like to reuse); and
    5) Within PD: expresses special kinds of roles, transactions, or things.
    Why are you trying to force these mystery methodsfrom the superclass?
    It's not mandatory for me to do it... I 'd see it
    just like a further way to check that the subclasses
    implements these methods, as they have to do.That's not a good idea. If the superclass has no relation to the database, it shouldn't contain methods (abstract or otherwise) related to database transactions.
    The subclasses are the classes that handle db
    transaction.
    They are designed as a binding to a db table.And how is the superclass designed to handle db transactions? My guess (based on your description) is that it isn't. That should tell you right away that the subclasses should not extend your superclass.

  • Abstract class extends other class?

    What happens when a abstract class extends other class?
    How can we use the abstract class late in other class?
    Why do we need an abstract class that extends other class?
    for example:-
    public abstract class ABC extends EFG {
    public class EFG{
    private String name="";
    private int rollno="";
    private void setName(int name)
    this.name=name;
    private String getName()
    return this.name;
    }

    shafiur wrote:
    What happens when a abstract class extends other class?Nothing special. You have defined an abstract class.
    How can we use the abstract class late in other class?Define "Late". What "other class"?
    Why do we need an abstract class that extends other class?Because it can be useful to define one.

Maybe you are looking for

  • How to start midi event playing from the middle of event?

    I'm not sure if my post title is correct but... I have a two minute piece of music with various instruments playing.  There are some strings that play the same couple of notes throughout. At the moment I am working on a middle section but as I loop,

  • On doing a nice GREY with CMYK

    Hi guys, I know if I need a good solid and dark black i can always use an "enriched black" let´s say C=50, M=0, Y=0, K=100 I am doing a design which i will need a strong GREY, let´s say 80% black. The problem with that something the grey does not cov

  • Message in scheduled st

    Hi Friends,    Its a support issue. A message is in scheduled status(green flag) and when i try to restart i am getting error something like 'the message is already in scheduled state'. I heard that if we unlock the queue the issue can be resolved, I

  • Latest airport extreme

    how do i know if i have the latest verison, cause when i bought my imac on ebay it came with the airport card..any help apperciated. thanks

  • Selecting multiple rows of a table

    Hi Forum, How to select multiple rows of a table at a time? Please help me.. Thanks Swapna