Abstract class reference itself

How do I reference an abstract class to itself.
public abstract class SomeClass {
   public static SomeType SomeMethod(){
         SomeClass mine = new SomeClass();
   }It gives me an error saying it can not instantiate the class.

Possible source of confusion: you can declare a variable of type abstract class and assign it an object of a derived class that fully implements the abstract class. For instance:
abstract class SomeClass
     public static void SomeMethod(){}
     public abstract void greeting();
class AnotherClass extends SomeClass
     public void greeting()
          System.out.println("hello");
public class DemoAbstractClasses
     public static void main(String args[])
          SomeClass A = new AnotherClass(); // A's type is an abstract class
          A.greeting();  //polymorphism
}

Similar Messages

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

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

  • Abstract method called in an abstract class

    Hello,
    I am writing some code that I'd like to be as generic as possible.
    I created an abstract class called Chromozome. This abstract class has a protected abstract method called initialize().
    I also created an abstract class called Algorithm which contains a protected ArrayList<Chromozome>.
    I would like to create a non abstract method (called initializePopulation()) which would create instances of Chromozome, call their method initialize() and full the ArrayList with them.
    In a practical matter, only subclass of Algorithm will be used, using an ArrayList of a subclass of Chromozome implementing their own version of initialize.
    I have been thinking of that and concluded it was impossible to do. But I'd like to ask more talented peaple before forgetting it !
    Thanks,
    Vincent

    Ok, let's it is not impossible, juste that I had no idea of how doing it :-)
    The difficulty is that Algorithm will never have to deal with Chromozome itself, but always with subclass of Chromozome. This is usually not an issue, but in that case, Algorithm is required to create instances of the desired subclass of Chromozome, but without knowing in advance wich subclass will be used (I hope what I say makes any sense).
    Actually I may have found a way in the meantime, but maybe not the best one.
    I created in Algorithm an abstract method :
    protected abstract Chromozome createChromozome()The method initializePopulation will call createChromozome instead of calling directly the constructor and the initialize() method of Chromozome.
    Then subclass of Algorithm will implement the method createChromozome using the desired subclass of Chromozome.

  • Final field in abstract class

    Hi ... consider the code:abstract class It {
         protected final boolean
              USE;
    public class Test extends It {
         public Test(){
              USE = true;
    } upon compiling there is an error (infact, two errors).
    final may not be assigned, can't assign to final.
    of course, if "It" was not abstract, the first error might be true ... but it is abstract, so
    shouldn't this checking of assignment to final be delayed until the class is inheritied
    as concrete ? it would seem to make sense ... i can't see a reason for this not being
    the case.
    if it was the case, we could delay assignment until our constructor of "Test" where it
    would assign to the final variable of "It".
    it shouldn't be an error, should it ?
    java version:java version "1.4.2_03"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_03-b02)
    Java HotSpot(TM) Client VM (build 1.4.2_03-b02, mixed mode)

    is it because references to the final fields are resolved at compile-time ?
    such that the compiler must know the value of USE in:if(USE){
      // a
    // b at compile time so it can remove either "b" or "a". I think so. hmm.

  • Lookinf for a "flexible" abstract class mechanism

    When writing an abstract class, or an interface, is there a way to force the classes who extends it to implement at least one method in a set of 2 ?
    For instance,
    public abstract class PermanentCard {
       public void concretePlayByPlayer(Player parPlayer);
       public void concretePlayByPlayer(Player parPlayer, Location parLocation);
    }In this case, I'd like to say that all class who implement PermanentCard must implement at least one these two methods.
    Is there a way to avoid multiplying the number of abstract I have?

    bestam wrote:
    To BigDaddy :
    Consider I have an abstract class who expects its implementations to implement a concretePlay method, whatever is its signature. Of course, java is only able to distinguish methods via their signatures.
    I was just looking for non-direct way to let the implementations implement one or another, but at least one.
    Supposing you did that, how is the code using the interface to know which method(s) are available in this particular implementation? An interface is a contract, and the user is entitled to expect that contract to be fulfilled.
    If you have some classes which do things one way, and some the other, it would be better to put the two method signatures in different interfaces, in which case the code using the class could us instanceof to test which method signature was actually available.
    The two interfaces could extend a common, possibly empty one for references that might hold either.
    Of course in this particular case using the same signature with a null argument is more satisfactory.
    Edited by: malcolmmc on May 14, 2009 9:20 AM

  • Modify Standard Abstract Classes.

    I would like to know what is the approach to extend a
    Standard Delivered Abstract Class.
    I tried the following approach, but it doesnt seem to work.
    I want to add some methods to the standard Abstract Class
    CL_CRM_AUI_ENTITY. So i created a copy(not inheritance )
    -> ZCL_CRM_AUI_ENTITY and added a new abstract method to this class.
    The Class CL_CRM_AUI_ONEORDER implements the methods of the abstract class. I implemented the new method here.
    Now in my Application :
    The following code works  - <b>Reference to the standard delivered abstract class cl_crm_aui_entity.</b>
    data : lv_bol_entity type ref to cl_crm_bol_entity      lv_aui_entity type ref to cl_crm_aui_entity.
    IF lv_bol_entity is bound.
    lv_aui_entity ?= lv_bol_entity.
    ENDIF.
    The following code <b>does not</b> work and gives me a CX_SY_MOVE_CAST_ERROR.
    data : lv_bol_entity type ref to cl_crm_bol_entity,
           lv_aui_entity type ref to <i><b>zcl_crm_aui_entity</b></i>.
    IF lv_bol_entity is bound.
    lv_aui_entity ?= lv_bol_entity.
      CATCH...
      ENDCATCH.
    ENDIF.
    Is the solution then to modify the standard delivered abstract class or can we work around this?
    Thanks.

    Decorators work well if a Class define an interface. Using decorators gives the power to add multiple features which can freely combined without creating all combinations of classes.
    If e.g. you want to enable tracing of each method you implement a trace decorator and put in the original implementation. Another decorator may due additonal security checks. If you now want to combine both you just can put the original instance in the first decorator and then in the second. With single inheritance you may need much more classes.
    But similar to inheritance, the instances of the base class wont be able to call instances of the encapsulation. The decorator can replace or enrich the base class only.
    I wonder why you want to make the original class to use your changes. Is it not sufficient that all programs using your enriched instances work with your additions.
    Kind Regards
    Klaus

  • Question about Abstract Classes and Class Inheritance

    The semester is winding down, and the assignments are getting more complicated....
    Prof has given us a project involving both an interface and an abstract class. There's a class Person, then an abstract class Employee that extends Person, and two types of Employees (Hourly and Salaried) that extend Employee. The finished assignment is a type of payroll program that's supposed to be able to store both types of Employees and related info (name, salary, etc). One thing the prof suggested was to store both HourlyEmployees and SalariedEmployees in an array of Employees. But you can't instantiate an array of Employees directly, of course, since it's an abstract class.
    So is it possible to create an array of Persons, cast either HourlyEmployees or SalariedEmployees into Employee objects, and then store the Employee objects in the Person array? And if I do that, can I still use methods particular to the SalariedEmployees and/or HourlyEmployees once they are in the Person array? Or can I store SalariedEmployee and HourlyEmployee directly in an array of Persons, without having to cast them into anything else? (In that case, I'm not sure what the point of having the abstract Employee class is, though). Do they become just generic "Persons" if I do this?
    Thanks for any help!

    But you
    can't instantiate an array of Employees directly, of
    course, since it's an abstract class.Sure you can. You just can't instantiate Employee (the abstact class itself, as opposed to its subclasses) objects.
    Employee[] employees = new Employee[20];
    employees[0] = new HourlyEmployee();That should work.
    So is it possible to create an array of Persons, cast
    either HourlyEmployees or SalariedEmployees into
    Employee objects, and then store the Employee objects
    in the Person array?You could do that as well, but you shouldn't need to cast it.
    Given the type hierarchy you describe, an HourlyEmployee is a Person, so you should be able to assign an HourlyEmployee directly to a Person-valued variable.
    And if I do that, can I still use
    methods particular to the SalariedEmployees and/or
    HourlyEmployees once they are in the Person array?No. If the method doesn't exist in Person, then you can't call it on a Person variable, even if the method does exist in the class implementing Person.
    But if the method exists in Person, but is implemented and possibly overridden in HourlyEmployee, you can still invoke it, by just invoking the Person method.
    public interface Person {
      public void feed();
    public abstract class Employee implements Person {
      public abstract void hire();
    public class HourlyEmployee extends Employee {
    // then:
    Person persons = new Person[20];
    // add HourlyEmployees or SalariedEmployees to persons array...
    persons[0].feed(); // OK!
    persons[0].hire(); // NOT OK!

  • Abstract Class & Interfaces

    Can anyone please tell me as to why we need both an abstract class & an interface? I was asked in an interview as to why we need 2 separate concepts when we can get the similar functionality of an interface by using an abstract class. I had just sited their differences like:
    1) An abstract class can have both abstract & normal methods & that we can specify different access specifiers for its class members.
    2) ABAP does not support Multiple inheritance but that we could simulate the same using interfaces concept in ABAP.
    But he wasnt satisfied with the answer. I guess he was expecting something from a practical point of view. I did try searching the old threads but there wasnt anything similar to this. Anyone please explain by citing a scenario as to why we would need 2 separate concepts & not just one .
    Thanks in advance

    Hi
    Abstract classes
    Abstract classes are normally used as an incomplete blueprint for concrete (that is, non-abstract) subclasses, for example to define a uniform interface.
    Classes with at least one abstract method are themselves abstract.
    Static methods and constructors cannot be abstract.
    You can specify the class of the instance to be created explicitly: CREATE OBJECT <RefToAbstractClass> TYPE <NonAbstractSubclassName>.
    Abstarct classes themselves can’t be instantiated ( althrough their subclasses can)
    Reference to abstract classes can refer to instance of subclass
    Abstract (instance) methods are difined in the class , but not implemented
    They must be redefined in subclasses
    CLASS LC1 DEFINAITION ABSTARCT
    PUBLIC SECTION
    METHODS ESTIMATE ABSTARCT IMPORTING…
    ENDCLASS.
    <b>Interfaces</b>
    Interfaces only describe the external point of contact of a class (protocols), they do not contain any implementation.
    Interfaces are usually defined by a user. The user describes in the interface which services (technical and semantic) it needs in order to carry out a task.
    The user never actually knows the providers of these services, but communicates with them through the interface.
    In this way the user is protected from actual implementations and can work in the same way with different classes/objects, as long as they provide the services required. This is known as polymorphism with interfaces.

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

    I'm confused. Is this true or false.
    The great thing about polymorphism is that you can call one method. If the subclass inherited that method, it will be customized and perform a different duty. That way, the action it performs will depend on 1>whether or not it's a sub or super class and also 2>if the method was overridden if it was a subclass.
    Now, my confusion. If an object reference is to a Super-abstract-class... how do the method calls and properties go?? well let me let you answer for me. Thanks so much in advance for this clarification.

    Yes. You are - pretty much.
    The abstract class, as such, can never be instantiated. BUT a class derived from the superclass IS an instance of the superclass.
    Silly example:
    abstract public class Animal {
       public Animal() {
       public abstract int getNumberOfLegs();
    }That's our animal class, and we know that anything that's an animal has a number of legs - but we can't just create a "generic" animal.
    public class Cat extends Animal {
       public Cat() {
          super();
       public int getNumberOfLegs() {
          return legCount;
       public void maim(int legsToRemove) {
          legCount -= legsToRemove;
          if(legCount < 0 ) legCount = 0;
       private int legCount = 4;
    }A Cat is a specific type of animal, so we can find out how many legs it has (usually 4). Note again that a cat IS an animal, so Cat IS an instance of Animal.
    Java even provides a special operator to test this:
    Cat cat = new Cat();
    System.out.println("A cat is a cat: " + (cat instanceof Cat));
    System.out.println("A cat is an animal: " + (cat instanceof Animal));The term used to describe the "Guarantee" that a subclass of an abstract class (or an implementation of an interface) is usually and technically a "contract", but I prefer to think of it as a "Promise" since you can break the promise by messing with the bytecode - at which point the JVM will spot the lie and complain !
    D.

  • Abstract class instantiation.?

    I have an Abstract class which is extended
    My question is:
    How can the Abstract class be instantiated:
    Animal[] ref = new Animal[3];
    In Java,we cannot instantiate Abstract class,so how does this
    work
    abstract class Animal  // class is abstract
      private String name;
      public String getName(){       
           return name;
      public abstract void speak();  
    class Dog extends Animal{
          private String dogName;
          public Dog(String nm){
         this.dogName=nm;
          public void speak(){       // Implement the abstract method.
          System.out.println("Woof");
          public String getName(){   // Override default functionality.
              return dogName;
    class Cow extends Animal{
          private String cowName;
          public Cow(String nm){
          this.cowName = nm;
          public void speak(){       // Implement the abstract method.
          System.out.println("Moo");
          public String getName(){
              return cowName;
    public class AnimalArray{
      public static void main(String[] args) {
      Animal[] ref = new Animal[3]; // assign space for array
      Dog aDog = new Dog("Rover");  // makes specific objects
      Cow aCow = new Cow("Bossy"); 
      // now put them in an array
      ref[0] = aDog;
      ref[1] = aCow;
      // now dynamic method binding
      for (int x=0;x<2;++x){
           ref[x].speak();
           System.out.println(ref[x].getName());
    }

    You mean to say that now we have a handle or a reference to the
    abstract class. Right ?
    But in the
    public static Test instance () {
            return new Test () {
                public void test () {}
        }How can you say 'return new Test()' as Test is an abtract class
    and what will public void test() return as this has no body ?

  • Abstract Class & Interface

    Hi ,
    I have a fundamental doubt regarding Abstract Class & Interface!!!
    What is their real benefit...whether we implement an interface or extend an Abstract class we have to write the code for the abstract method in the concrete class.Then where the benefit remained....
    And it is said that Abstract class provide default behaviour...what is the actual meaning of that?
    Thanks & Regards
    Santosh

    In this section we will redesign our OneRowNim game to fit within a hierarchy of classes of two-player games. There are many games that characteristically involve two players: checkers, chess, tic-tac-toe, guessing games, and so forth. However, there are also many games that involve just one player: blackjack, solitaire, and others. There are also games that involve two or more players, such as many card games. Thus, our redesign of OneRowNim as part of a two-player game hierarchy will not be our last effort to design a hierarchy of game-playing classes. We will certainly redesign things as we learn new Java language constructs and as we try to extend our game library to other kinds of games.
    This case study will illustrate how we can apply inheritance and polymorphism, as well as other object-oriented design principles. The justification for revising OneRowNim at this point is to make it easier to design and develop other two-player games. As we have seen, one characteristic of class hierarchies is that more general attributes and methods are defined in top-level classes. As one proceeds down the hierarchy, the methods and attributes become more specialized. Creating a subclass is a matter of specializing a given class.
    8.6.1. Design Goals
    One of our design goals is to revise the OneRowNim game so that it fits into a hierarchy of two-player games. One way to do this is to generalize the OneRowNim game by creating a superclass that contains those attributes and methods that are common to all two-player games. The superclass will define the most general and generic elements of two-player games. All two-player games, including OneRowNim, will be defined as subclasses of this top-level superclass and will inherit and possibly override its public and protected variables and methods. Also, our top-level class will contain certain abstract methods, whose implementations will be given in OneRowNim and other subclasses.
    Generic superclass
    A second goal is to design a class hierarchy that makes it possible for computers to play the game, as well as human users. Thus, for a given two-player game, it should be possible for two humans to play each other, or for two computers to play each other, or for a human to play against a computer. This design goal will require that our design exhibit a certain amount of flexibility. As we shall see, this is a situation in which Java interfaces will come in handy.
    [Page 376]
    Another important goal is to design a two-player game hierarchy that can easily be used with a variety of different user interfaces, including command-line interfaces and GUIs. To handle this feature, we will develop Java interfaces to serve as interfaces between our two-player games and various user interfaces.
    8.6.2. Designing the TwoPlayerGame Class
    To begin revising the design of the OneRowNim game, we first need to design a top-level class, which we will call the TwoPlayerGame class. What variables and methods belong in this class? One way to answer this question is to generalize our current version of OneRowNim by moving any variables and methods that apply to all two-player games up to the TwoPlayerGame class. All subclasses of TwoPlayerGamewhich includes the OneRowNim classwould inherit these elements. Figure 8.18 shows the current design of OneRowNim.
    Figure 8.18. The current OneRowNim class.
    What variables and methods should we move up to the TwoPlayerGame class? Clearly, the class constants, PLAYER_ONE and PLAYER_TWO, apply to all two-player games. These should be moved up. On the other hand, the MAX_PICKUP and MAX_STICKS constants apply just to the OneRowNim game. They should remain in the OneRowNim class.
    The nSticks instance variable is a variable that only applies to the OneRowNim game but not to other two-player games. It should stay in the OneRowNim class. On the other hand, the onePlaysNext variable applies to all two-player games, so we will move it up to the TwoPlayerGame class.
    Because constructors are not inherited, all of the constructor methods will remain in the OneRowNim class. The instance methods, takeSticks() and getSticks(), are specific to OneRowNim, so they should remain there. However, the other methods, getPlayer(), gameOver(), getWinner(), and reportGameState(), are methods that would be useful to all two-player games. Therefore these methods should be moved up to the superclass. Of course, while these methods can be defined in the superclass, some of them can only be implemented in subclasses. For example, the reportGameState() method reports the current state of the game, so it has to be implemented in OneRowNim. Similarly, the getWinner() method defines how the winner of the game is determined, a definition that can only occur in the subclass. Every two-player game needs methods such as these. Therefore, we will define these methods as abstract methods in the superclass. The intention is that TwoPlayerGame subclasses will provide game-specific implementations for these methods.
    [Page 377]
    Constructors are not inherited
    Given these considerations, we come up with the design shown in Figure 8.19. The design shown in this figure is much more complex than the designs used in earlier chapters. However, the complexity comes from combining ideas already discussed in previous sections of this chapter, so don't be put off by it.
    Figure 8.19. TwoPlayerGame is the superclass for OneRowNim and other two-player games.
    To begin with, note that we have introduced two Java interfaces into our design in addition to the TwoPlayerGame superclass. As we will show, these interfaces lead to a more flexible design and one that can easily be extended to incorporate new two-player games. Let's take each element of this design separately.
    [Page 378]
    8.6.3. The TwoPlayerGame Superclass
    As we have stated, the purpose of the TwoPlayerGame class is to serve as the superclass for all two-player games. Therefore, it should define the variables and methods shared by two-player games.
    The PLAYER_ONE, PLAYER_TWO, and onePlaysNext variables and the getPlayer(), setPlayer(), and changePlayer() methods have been moved up from the OneRowNim class. Clearly, these variables and methods apply to all two-player games. Note that we have also added three new variables, nComputers, computer1, computer2, and their corresponding methods, getNComputers() and addComputerPlayer(). We will use these elements to give our games the capability to be played by computer programs. Because we want all of our two-player games to have this capability, we define these variables and methods in the superclass rather than in OneRowNim and subclasses of TwoPlayerGame.
    Note that the computer1 and computer2 variables are declared to be of type IPlayer. IPlayer is an interface containing a single method declaration, the makeAMove() method:
    public interface IPlayer {
    public String makeAMove(String prompt);
    Why do we use an interface here rather than some type of game-playing object? This is a good design question. Using an interface here makes our design more flexible and extensible because it frees us from having to know the names of the classes that implement the makeAMove() method. The variables computer1 and computer2 will be assigned objects that implement IPlayer via the addComputerPlayer() method.
    Game-dependent algorithms
    The algorithms used in the various implementations of makeAMove() are game-dependentthey depend on the particular game being played. It would be impossible to define a game playing object that would suffice for all two-player games. Instead, if we want an object that plays OneRowNim, we would define a OneRowNimPlayer and have it implement the IPlayer interface. Similarly, if we want an object that plays checkers, we would define a CheckersPlayer and have it implement the IPlayer interface. By using an interface here, our TwoPlayerGame hierarchy can deal with a wide range of differently named objects that play games, as long as they implement the IPlayer interface. Using the IPlayer interface adds flexibility to our game hierarchy and makes it easier to extend it to new, yet undefined, classes. We will discuss the details of how to design a game player in Section 8.6.7.
    The IPlayer interface
    Turning now to the methods defined in TwoPlayerGame, we have already seen implementations of getPlayer(), setPlayer(), and changePlayer() in the OneRowNim class. We will just move those implementations up to the superclass. The getNComputers() method is the assessor method for the nComputers variable, and its implementation is routine. The addComputerPlayer() method adds a computer player to the game. Its implementation is as follows:
    [Page 379]
    public void addComputerPlayer(IPlayer player) {
    if (nComputers == 0)
    computer2 = player;
    else if (nComputers == 1)
    computer1 = player;
    else
    return; // No more than 2 players
    ++nComputers;
    As we noted earlier, the classes that play the various TwoPlayerGames must implement the IPlayer interface. The parameter for this method is of type IPlayer. The algorithm we use checks the current value of nComputers. If it is 0, which means that this is the first IPlayer added to the game, the player is assigned to computer2. This allows the human user to be associated with PLAYERONE if this is a game between a computer and a human user.
    If nComputers equals 1, which means that we are adding a second IPlayer to the game, we assign that player to computer1. In either of these cases, we increment nComputers. Note what happens if nComputers is neither 1 nor 2. In that case, we simply return without adding the IPlayer to the game and without incrementing nComputers. This, in effect, limits the number of IPlayers to two. (A more sophisticated design would throw an exception to report an error. but we will leave that for a subsequent chapter.)
    The addComputerPlayer() method is used to initialize a game after it is first created. If this method is not called, the default assumption is that nComputers equals zero and that computer1 and computer2 are both null. Here's an example of how it could be used:
    OneRowNim nim = new OneRowNim(11); // 11 sticks
    nim.add(new NimPlayer(nim)); // 2 computer players
    nim.add(new NimPlayerBad(nim));
    Note that the NimPlayer() constructor takes a reference to the game as its argument. Clearly, our design should not assume that the names of the IPlayer objects would be known to the TwoPlayerGame superclass. This method allows the objects to be passed in at runtime. We will discuss the details of NimPlayerBad in Section 8.6.7.
    The getrules() method is a new method whose purpose is to return a string that describes the rules of the particular game. This method is implemented in the TwoPlayerGame class with the intention that it will be overridden in the various subclasses. For example, its implementation in TwoPlayerGame is:
    public String getRules() {
    return "The rules of this game are: ";
    Overriding a method
    [Page 380]
    and its redefinition in OneRowNim is:
    public String getRules() {
    return "\n*** The Rules of One Row Nim ***\n" +
    "(1) A number of sticks between 7 and " + MAX_STICKS +
    " is chosen.\n" +
    "(2) Two players alternate making moves.\n" +
    "(3) A move consists of subtracting between 1 and\n\t" +
    MAX_PICKUP +
    " sticks from the current number of sticks.\n" +
    "(4) A player who cannot leave a positive\n\t" +
    " number of sticks for the other player loses.\n";
    The idea is that each TwoPlayerGame subclass will take responsibility for specifying its own set of rules in a form that can be displayed to the user.
    You might recognize that defining geTRules() in the superclass and allowing it to be overridden in the subclasses is a form of polymorphism. It follows the design of the toString() method, which we discussed earlier. This design will allow us to use code that takes the following form:
    TwoPlayerGame game = new OneRowNim();
    System.out.println(game.getRules());
    Polymorphism
    In this example the call to getrules() is polymorphic. The dynamic-binding mechanism is used to invoke the getrules() method defined in the OneRowNim class.
    The remaining methods in TwoPlayerGame are defined abstractly. The gameOver() and getWinner() methods are both game-dependent methods. That is, the details of their implementations depend on the particular TwoPlayerGame subclass in which they are implemented.
    This is good example of how abstract methods should be used in designing a class hierarchy. We give abstract definitions in the superclass and leave the detailed implementations up to the individual subclasses. This allows the different subclasses to tailor the implementations to their particular needs, while allowing all subclasses to share a common signature for these tasks. This enables us to use polymorphism to create flexible, extensible class hierarchies.
    Figure 8.20 shows the complete implementation of the abstract TwoPlayerGame class. We have already discussed the most important details of its implementation.
    Figure 8.20. The TwoPlayerGame class
    (This item is displayed on page 381 in the print version)
    public abstract class TwoPlayerGame {
    public static final int PLAYER_ONE = 1;
    public static final int PLAYER_TWO = 2;
    protected boolean onePlaysNext = true;
    protected int nComputers = 0; // How many computers
    // Computers are IPlayers
    protected IPlayer computer1, computer2;
    public void setPlayer(int starter) {
    if (starter == PLAYER_TWO)
    onePlaysNext = false;
    else onePlaysNext = true;
    } // setPlayer()
    public int getPlayer() {
    if (onePlaysNext)
    return PLAYER_ONE;
    else return PLAYER_TWO;
    } // getPlayer()
    public void changePlayer() {
    onePlaysNext = !onePlaysNext;
    } // changePlayer()
    public int getNComputers() {
    return nComputers;
    } // getNComputers()
    public String getRules() {
    return "The rules of this game are: ";
    } // getRules()
    public void addComputerPlayer(IPlayer player) {
    if (nComputers == 0)
    computer2 = player;
    else if (nComputers == 1)
    computer1 = player;
    else
    return; // No more than 2 players
    ++nComputers;
    } // addComputerPlayer()
    public abstract boolean gameOver(); // Abstract Methods
    public abstract String getWinner();
    } // TwoPlayerGame class
    Effective Design: Abstract Methods
    Abstract methods allow you to give general definitions in the superclass and leave the implementation details to the different subclasses.
    [Page 381]
    8.6.4. The CLUIPlayableGame Interface
    We turn now to the two interfaces shown in Figure 8.19. Taken together, the purpose of these interfaces is to create a connection between any two-player game and a command-line user interface (CLUI). The interfaces provide method signatures for the methods that will implement the details of the interaction between a TwoPlayerGame and a UserInterface. Because the details of this interaction vary from game to game, it is best to leave the implementation of these methods to the games themselves.
    Note that CLUIPlayableGame extends the IGame interface. The IGame interface contains two methods that are used to define a standard form of communication between the CLUI and the game. The getGamePrompt() method defines the prompt used to signal the user for a move of some kindfor example, "How many sticks do you take (1, 2, or 3)?" And the reportGameState() method defines how the game will report its current statefor example, "There are 11 sticks remaining." CLUIPlayableGame adds the play() method to these two methods. As we will see shortly, the play() method contains the code that will control the playing of the game.
    [Page 382]
    Extending an interface
    The source code for these interfaces is very simple:
    public interface CLUIPlayableGame extends IGame {
    public abstract void play(UserInterface ui);
    public interface IGame {
    public String getGamePrompt();
    public String reportGameState();
    } // IGame
    Note that the CLUIPlayableGame interface extends the IGame interface. A CLUIPlayableGame is a game that can be played through a CLUI. The purpose of its play() method is to contain the game-dependent control loop that determines how the game is played via a user interface (UI). In pseudocode, a typical control loop for a game would look something like the following:
    Initialize the game.
    While the game is not over
    Report the current state of the game via the UI.
    Prompt the user (or the computer) to make a move via the UI.
    Get the user's move via the UI.
    Make the move.
    Change to the other player.
    The play loop sets up an interaction between the game and the UI. The UserInterface parameter allows the game to connect directly to a particular UI. To allow us to play our games through a variety of UIs, we define UserInterface as the following Java interface:
    public interface UserInterface {
    public String getUserInput();
    public void report(String s);
    public void prompt(String s);
    Any object that implements these three methods can serve as a UI for one of our TwoPlayerGames. This is another example of the flexibility of using interfaces in object-oriented design.
    To illustrate how we use UserInterface, let's attach it to our KeyboardReader class, thereby letting a KeyboardReader serve as a CLUI for TwoPlayerGames. We do this simply by implementing this interface in the KeyboardReader class, as follows:
    public class KeyboardReader implements UserInterface
    [Page 383]
    As it turns out, the three methods listed in UserInterface match three of the methods in the current version of KeyboardReader. This is no accident. The design of UserInterface was arrived at by identifying the minimal number of methods in KeyboardReader that were needed to interact with a TwoPlayerGame.
    Effective Design: Flexibility of Java Interfaces
    A Java interface provides a means of associating useful methods with a variety of different types of objects, leading to a more flexible object-oriented design.
    The benefit of defining the parameter more generally as a UserInterface instead of as a KeyboardReader is that we will eventually want to allow our games to be played via other kinds of command-line interfaces. For example, we might later define an Internet-based CLUI that could be used to play OneRowNim among users on the Internet. This kind of extensibilitythe ability to create new kinds of UIs and use them with TwoPlayerGamesis another important design feature of Java interfaces.
    Generality principle
    Effective Design: Extensibility and Java Interfaces
    Using interfaces to define useful method signatures increases the extensibility of a class hierarchy.
    As Figure 8.19 shows, OneRowNim implements the CLUIPlayableGame interface, which means it must supply implementations of all three abstract methods: play(), getGamePrompt(), and reportGameState().
    8.6.5. Object-Oriented Design: Interfaces or Abstract Classes?
    Why are these methods defined in interfaces? Couldn't we just as easily define them in the TwoPlayerGame class and use inheritance to extend them to the various game subclasses? After all, isn't the net result the same, namely, that OneRowNim must implement all three methods.
    These are very good design questions, exactly the kinds of questions one should ask when designing a class hierarchy of any sort. As we pointed out in the Animal example earlier in the chapter, you can get the same functionality from an abstract interface and an abstract superclass method. When should we put the abstract method in the superclass, and when does it belong in an interface? A very good discussion of these and related object-oriented design issues is available in Java Design, 2nd Edition, by Peter Coad and Mark Mayfield (Yourdan Press, 1999). Our discussion of these issues follows many of the guidelines suggested by Coad and Mayfield.
    Interfaces vs. abstract methods
    We have already seen that using Java interfaces increases the flexibility and extensibility of a design. Methods defined in an interface exist independently of a particular class hierarchy. By their very nature, interfaces can be attached to any class, and this makes them very flexible to use.
    Flexibility of interfaces
    Another useful guideline for answering this question is that the superclass should contain the basic common attributes and methods that define a certain type of object. It should not necessarily contain methods that define certain roles that the object plays. For example, the gameOver() and getWinner() methods are fundamental parts of the definition of a TwoPlayerGame. One cannot define a game without defining these methods. By contrast, methods such as play(), getGamePrompt(), and reportGameState() are important for playing the game but they do not contribute in the same way to the game's definition. Thus these methods are best put into an interface. Therefore, one important design guideline is:
    [Page 384]
    Effective Design: Abstract Methods
    Methods defined abstractly in a superclass should contribute in a fundamental way to the basic definition of that type of object, not merely to one of its roles or its functionality.
    8.6.6. The Revised OneRowNim Class
    Figure 8.21 provides a listing of the revised OneRowNim class, one that fits into the TwoPlayerGame class hierarchy. Our discussion in this section will focus on the features of the game that are new or revised.
    Figure 8.21. The revised OneRowNim class, Part I.
    (This item is displayed on page 385 in the print version)
    public class OneRowNim extends TwoPlayerGame implements CLUIPlayableGame {
    public static final int MAX_PICKUP = 3;
    public static final int MAX_STICKS = 11;
    private int nSticks = MAX_STICKS;
    public OneRowNim() { } // Constructors
    public OneRowNim(int sticks) {
    nSticks = sticks;
    } // OneRowNim()
    public OneRowNim(int sticks, int starter) {
    nSticks = sticks;
    setPlayer(starter);
    } // OneRowNim()
    public boolean takeSticks(int num) {
    if (num < 1 || num > MAX_PICKUP || num > nSticks)
    return false; // Error
    else // Valid move
    { nSticks = nSticks - num;
    return true;
    } // else
    } // takeSticks()
    public int getSticks() {
    return nSticks;
    } // getSticks()
    public String getRules() {
    return "\n*** The Rules of One Row Nim ***\n" +
    "(1) A number of sticks between 7 and " + MAX_STICKS +
    " is chosen.\n" +
    "(2) Two players alternate making moves.\n" +
    "(3) A move consists of subtracting between 1 and\n\t" +
    MAX_PICKUP + " sticks from the current number of sticks.\n" +
    "(4) A player who cannot leave a positive\n\t" +
    " number of sticks for the other player loses.\n";
    } // getRules()
    public boolean gameOver() {   /*** From TwoPlayerGame */
    return (nSticks <= 0);
    } // gameOver()
    public String getWinner() {        /*** From TwoPlayerGame */
    if (gameOver()) //{
    return "" + getPlayer() + " Nice game.";
    return "The game is not over yet."; // Game is not over
    } // getWinner()
    The gameOver() and getWinner() methods, which are nowinherited from the TwoPlayerGame superclass, are virtually the same as in the previous version. One small change is that getWinner() now returns a String instead of an int. This makes the method more generally useful as a way of identifying the winner for all TwoPlayerGames.
    Similarly, the getGamePrompt() and reportGameState() methods merely encapsulate functionality that was present in the earlier version of the game. In our earlier version the prompts to the user were generated directly by the main program. By encapsulating this information in an inherited method, we make it more generally useful to all TwoPlayerGames.
    Inheritance and generality
    The major change to OneRowNim comes in the play() method, which controls the playing of OneRowNim (Fig. 8.22). Because this version of the game incorporates computer players, the play loop is a bit more complex than in earlier versions of the game. The basic idea is still the same: The method loops until the game is over. On each iteration of the loop, one or the other of the two players, PLAYER_ONE or PLAYER_TWO, takes a turn making a movethat is, deciding how many sticks to pick up. If the move is a legal move, then it becomes the other player's turn.
    Figure 8.22. The revised OneRowNim class, Part II.
    (This item is displayed on page 386 in the print version)
    /** From CLUIPlayableGame */
    public String getGamePrompt() {
    return "\nYou can pick up between 1 and " +
    Math.min(MAX_PICKUP,nSticks) + " : ";
    } // getGamePrompt()
    public String reportGameState() {
    if (!gameOver())
    return ("\nSticks left: " + getSticks() +
    " Who's turn: Player " + getPlayer());
    else
    return ("\nSticks left: " + getSticks() +
    " Game over! Winner is Player " + getWinner() +"\n");
    } // reportGameState()
    public void play(UserInterface ui) { // From CLUIPlayableGame interface
    int sticks = 0;
    ui.report(getRules());
    if (computer1 != null)
    ui.report("\nPlayer 1 is a " + computer1.toString());
    if (computer2 != null)
    ui.report("\nPlayer 2 is a " + computer2.toString());
    while(!gameOver()) {
    IPlayer computer = null; // Assume no computers
    ui.report(reportGameState());
    switch(getPlayer()) {
    case PLAYER_ONE: // Player 1's turn
    computer = computer1;
    break;
    case PLAYER_TWO: // Player 2's turn
    computer = computer2;
    break;
    } // cases
    if (computer != null) {                           // If computer's turn
    sticks = Integer.parseInt(computer.makeAMove(""));
    ui.report(computer.toString() + " takes " + sticks + " sticks.\n");
    } else {                                          // otherwise, user's turn
    ui.prompt(getGamePrompt());
    sticks =
    Integer.parseInt(ui.getUserInput()); // Get user's move
    if (takeSticks(sticks)) // If a legal move
    changePlayer();
    } // while
    ui.report(reportGameState()); // The game is now over
    } // play()
    } // OneRowNim class
    Let's look now at how the code decides whether it is a computer's turn to move or a human player's turn. Note that at the beginning of the while loop, it sets the computer variable to null. It then assigns computer a value of either computer1 or computer2, depending on whose turn it is. But recall that one or both of these variables may be null, depending on how many computers are playing the game. If there are no computers playing the game, then both variables will be null. If only one computer is playing, then computer1 will be null. This is determined during initialization of the game, when the addComputerPlayer() is called. (See above.)
    In the code following the switch statement, if computer is not null, then we call computer.makeAMove(). As we know, the makeAMove() method is part of the IPlayer interface. The makeAMove() method takes a String parameter that is meant to serve as a prompt, and returns a String that is meant to represent the IPlayer's move:
    public interface IPlayer {
    public String makeAMove(String prompt);
    [Page 385]
    In OneRowNim the "move" is an integer, representing the number of sticks the player picks. Therefore, in play() OneRowNim has to convert the String into an int, which represents the number of sticks the IPlayer picks up.
    On the other hand, if computer is null, this means that it is a human user's turn to play. In this case, play() calls ui.getUserInput(), employing the user interface to input a value from the keyboard. The user's input must also be converted from String to int. Once the value of sticks is set, either from the user or from the IPlayer, the play() method calls takeSticks(). If the move is legal, then it changes whose turn it is, and the loop repeats.
    [Page 386]
    There are a couple of important points about the design of the play() method. First, the play() method has to know what to do with the input it receives from the user or the IPlayer. This is game-dependent knowledge. The user is inputting the number of sticks to take in OneRowNim. For a tic-tac-toe game, the "move" might represent a square on the tic-tac-toe board. This suggests that play() is a method that should be implemented in OneRowNim, as it is here, because OneRowNim encapsulates the knowledge of how to play the One-Row Nim game.
    Encapsulation of game-dependent knowledge
    [Page                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

  • Abstract class, Interface and two models issue

    Hi!
    I will post my code and then ask the question (text between code snippets is bold, so you don't miss it, it's not shouting):
    public class AppScreen extends JFrame
                           implements ActionListener {
      private MemoryTableModel model;
      public AppScreen() {
        this.model = new MemoryTableModel();
           //code
      public void actionPerformed(ActionEvent actEvt) {
          if(table.getSelectedRow() != -1) {
            model.deleteRow(table.getSelectedRow());
          else {
            ErrDialog.noRowErr();
      public MemoryTableModel getModel() {
        return model;
    public class MemoryTableModel extends BasicTableModel
                                  implements MemoryTableInterface {
      public MemoryTableModel() {
        //code
      public synchronized void insertRow(String file, String time) {
        //code
      public synchronized void editRow(int selectedRow, String file, String time) {
        //code
    public synchronized void deleteRow(int selectedRow) {
        //code
    public abstract class BasicTableModel extends AbstractTableModel {
      private final String FILE_COLUMN = "Executable file";
      private final String TIME_COLUMN = "Time";
      protected String[] columnNames   = new String[2];
      protected List<RowRecord> data   = new ArrayList<RowRecord>();
      BasicTableModel() {
        //code
      public int getColumnCount() {
        //code
      public int getRowCount() {
        //code
      public String getValueAt(int row, int col) {
        //code
      public Class<? extends String> getColumnClass(int c) {
        //code
      public String getColumnName(int col) {
        //code
      public List<RowRecord> getData() {
        //code
      public int getTimeColumn() {
        //code
      public int getFileColumn() {
        //code
    public interface MemoryTableInterface {
      public void insertRow(String file, String time);
      public void editRow(int selectedRow, String file, String time);
      public void deleteRow(int selectedRow);
    In this form, everything works fine. But now, I would like to choose between two models at the start, so I thought I would do this:
    public class AppScreen extends JFrame
                           implements ActionListener {
      private BasicTableModel model;
      public AppScreen() {
        if(...) {
          this.model = new MemoryTableModel();
        else {
          this.model = new JDBCTableModel();
    public void actionPerformed(ActionEvent actEvt) {
          if(table.getSelectedRow() != -1) {
            model.deleteRow(table.getSelectedRow());
          else {
            ErrDialog.noRowErr();
      public BasicTableModel getModel() {
        return model;
    public class JDBCTableModel extends BasicTableModel
                                implements JDBCTableInterface {
      public JDBCTableModel(Connection conn)
        throws ClassNotFoundException, SQLException {
        //code
      public void insertRow(String file, String time) throws SQLException {
        //code
      public void editRow(int selectedRow, String newFile, String newTime)
          throws SQLException {
        //code
      public void deleteRow(int selectedRow) throws SQLException {
        //code
    public interface JDBCTableInterface {
      public void insertRow(String file, String time) throws SQLException;
      public void editRow(int selectedRow, String file, String time)
          throws SQLException;
      public void deleteRow(int selectedRow) throws SQLException;
    }But I'm getting error message from AppScreen that method deleteRow(int) is undefined for the type BasicTableModel. I thought if I initialize variable model as some implementation of BasicTableModel, it will be OK. Apparently it's not, so:
    where and what am I missing or
    how can I realize this choosing between two models so I don't have to write "if(model == MemoryModel) else if(model == JDBCModel)" around every method where I have to decide.
    Thanks!

    I would like to have issues interfacing with two classy models, as well. ;-)
    You need to have your BasicTobleModel class implement your JDBCTableInterface interface (even if it doesn't implement those methods itself), if that is how you intend to use that class.
    Edit: Too slow.

  • Object oriented design problem concerning abstract classes and interfaces

    I have an abstract class (class A) that takes care of database connections. It cannot be made into an interface as other classes extend it and all these other classes require the functionality in the methods it has (i.e. I cannot make all the methods abstract and then make this class an interface).
    I have a class that contains data (Customer class) that I will create from the data I extract from the database. This class will also be created by the User and submitted to the database portion of the program. The Customer class has functionality in its methods which is required by the rest of the program (i.e. I cannot make all the methods abstract and then make this class an interface).
    I have a factory class (CustomerFactory) that extends the Customer class. This has been created to restrict access to the creation and manipulation of Customers.
    I have a class (DatabaseQuery) that extends class A. But now that I have retrieved all of the information that comprises a Customer from the database, I cannot construct a Customer without making reference to UserFactory. But UserFactory is a class that I don't want the database portion of the program to know about.
    What I would like to do is have my DatabaseQuery class extend both Customer class and A class. But they are both classes and Java won't allow that.
    I can't make either of the two classes that I want to make parents of DatabaseQuery into interfaces... so what can I do other than just keep a reference to UserFactory in my DatabaseQuery class?
    Thanks,
    Tim

    >
    What I would like to do is have my DatabaseQuery class
    extend both Customer class and A class. But they are
    both classes and Java won't allow that.
    I can't make either of the two classes that I want to
    make parents of DatabaseQuery into interfaces... so
    what can I do other than just keep a reference to
    UserFactory in my DatabaseQuery class?Just a guess...
    The description sounds a little vague but it sounds like the correct solution would be to refactor everything. The first clue is when I see "database connection" as an "abstract class". The only hierarchy that a database connection might exist in is in a connection pool and even that is probably shaky. It should never be part of data records, which is what your description sounds like.
    That probably isn't what you want to hear.
    The other solution, which is why refactoring is better (and which also makes it apparent why the original design is wrong) is to create an entire other hierarchy that mirrors your current data hierarchy and wraps it. So you now have "Customer", you will now have "Customer" and "DBCustomer". And all the code that currently uses "Customer" will have to start using DBCustomer. Actually it is easier than that since you can simply make the new class be "Customer" and rename the old class to "DBCustomer". Naturally that means the new class will have to have all of the functionality of the old class. Fortunately you can use the old class to do that. (But I would guess that isn't going to be easy.)

Maybe you are looking for