Beginner CORBA idl struct said to be abstract class

How do I instantiate a class declared in my .idl file for use by the methods implementing the interface?
I want to return an array of Record objects in my CORBA implentation, and my .idl file has:  struct Record
    long recordNumber;
    string firstName;
    string lastName;
    string streetAddress;
    string city;
    string country;
    string phone;
    string eMail;
    string fax;
     typedef sequence <Record> recordSet;
  interface AddRecord
    void setUser(in string user);
    string getUser();
        recordSet getRecords();
// plus more stuffWhen my implementing class in the server tries to define the getRecords() method like so:  public Record[] getRecords()
    Record r = null;
    Record[] allRecs;
    int index = 0;
    String selectAll = "SELECT * FROM Record ORDER BY Record_number";
    try
      Statement s = connection.createStatement();
      ResultSet recs = s.executeQuery(selectAll);
      while(recs.next())
        index++;
      allRecs = new Record[index];
//plus more stuffthe compiler complains
C:\My Documents\Java\CIS 290\hw5\RecordObj.java:178: Record is abstract; cannot be instantiated
r = new Record();
I went into the Record.java that the idlj compiler generated, and it is a final, non-abstract class. What incantation do I need here?

Whoops; solved that one; the real question is this: My .idl file declares some methods that I want to call in my implementation, but the .java class generated by the idlj compiler doesn't show the methods. Here's the full idl:module hw5Corba
typedef sequence <string> columns;
  struct Record
    long recordNumber;
    string firstName;
    string lastName;
    string streetAddress;
    string city;
    string country;
    string phone;
    string eMail;
    string fax;
   typedef sequence <Record> recordSet;
  interface AddRecord
   void setUser(in string user);
    string getUser();
   recordSet getRecords();
    columns getColumnNames(in string user);
    void newRecord(in Record r);
    void deleteRecord(in long num);
    void updateRecord(in Record r);
    void setRecordNumber(in long num);
    long getRecordNumber();
    void setFirstName(in string first);
    string getFirstName();
    void setLastName(in string last);
    string getLastName();
    void setStreetAddr(in string add);
    string getStreetAddr();
    void setCity(in string city);
    string getCity();
    void setCountry(in string country);
    string getCountry();
    void setEmail(in string email);
    string getEmail();
    void setPhone(in string phone);
    string getPhone();
    void setFax(in string fax);
    string getFax();
};Here's the method I expect to be able to implement:  public Record[] getRecords()
    Record r = null;
    Record[] allRecs;
    int index = 0;
    String selectAll = "SELECT * FROM Record ORDER BY Record_number";
    try
      Statement s = connection.createStatement();
      ResultSet recs = s.executeQuery(selectAll);
      while(recs.next())
        index++;
      allRecs = new Record[index];
      //cycle through records again, adding each
      //to the array
      index = 0;
      recs = s.executeQuery(selectAll);
      while(recs.next())
        r = new Record();
        r.setRecordNumber(recs.getInt(1));
        r.setFirstName(recs.getString(2));
        r.setLastName(recs.getString(3));
        r.setStreetAddr(recs.getString(4));
        r.setCity(recs.getString(5));
        r.setCountry(recs.getString(6));
        r.setEmail(recs.getString(7));
        r.setPhone(recs.getString(8));
        r.setFax(recs.getString(9));
        allRecs[index] = r;
      catch (SQLException ex)
        exceptionCode(ex);
    return allRecs;
  }The compiler error lists the 9 sub-methods as "can't resolve symbol", because as the Record.java file generated by the idlj shows, the methods aren't there:package hw5Corba;
* hw5Corba/Record.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Record.idl
* Tuesday, November 20, 2001 10:08:15 PM CST
public final class Record implements org.omg.CORBA.portable.IDLEntity
  public int recordNumber = (int)0;
  public String firstName = null;
  public String lastName = null;
  public String streetAddress = null;
  public String city = null;
  public String country = null;
  public String phone = null;
  public String eMail = null;
  public String fax = null;
  public Record ()
  } // ctor
  public Record (int _recordNumber,
String _firstName, String _lastName,
String _streetAddress, String _city,
String _country, String _phone,
String _eMail, String _fax)
    recordNumber = _recordNumber;
    firstName = _firstName;
    lastName = _lastName;
    streetAddress = _streetAddress;
    city = _city;
    country = _country;
    phone = _phone;
    eMail = _eMail;
    fax = _fax;
  } // ctor
} // class Record What do I need to do to implement these methods declared in the .idl file?

Similar Messages

  • How can I analyse corba idl files just as xml files are analysed by dom api

    I want to analyse and control corba idl files just like xml. We know that xml can be controled with org.omg.dom api, every element in xml can be read and write.But now, I want to realize a small program which can read every element in idl (eg. module, interface, methord) and auto-produce a element-tree. How can I do? Have dom api for idl files?

    You need a parser - try Antlr (http://www.antlr.org/). I believe it comes with an IDL grammar.
    Chuck

  • Why use an Abstract Class ?

    I am new to Java and for some reason I can't get my head around why to use an abstract class. I understand that an abstract class is something like:
    public abstract class Food{ // abstract class
    public void eat(){
    // stub
    public class Apple extends Food{
    public void eat(){
    // Eat an apple code
    }So basically the idea above is that you can eat an "apple" but you can't eat "food" because you can't instantiate an abstract class.
    I understand what an abstract class is and how to write one. What I don't understand is why you would use it? It looks to me like I could have just created a normal class called "Food" and just not instantiated it. What are the benefits of using an abstract class?

    807479 wrote:
    I am new to Java and for some reason I can't get my head around why to use an abstract class.One of the first books I ever read about Object-Oriented design contained the following quote from [url http://en.wikipedia.org/wiki/Lucius_Cary,_2nd_Viscount_Falkland]Lord Falkland:
    "When it is not necessary to make a decision, it is necessary +not+ to make a decision."
    It took me quite a while to understand, but it's all about flexibility: As soon as you cast something in stone, you lose the ability to change it later on if something better/more appropriate comes along. Interfaces and abstract classes are all about delaying that decision.
    As jverd said, interfaces allow you to specify what is required without defining the how; and as ErasP said, abstract classes are usually incomplete: ie, they define some of the 'how', but not all of it.
    What is most important about abstract classes though is that they cannot exist on their own: They must be extended by a concrete class that completes the 'how' before they can be instantiated and, as such, they declare the intent of the designer.
    One of the most important uses of abstract classes is as "skeleton implementations" of interfaces, and there are a lot of examples of these in the Java Collections hierarchy. My favourite is probably AbstractList, which contains a skeleton implementation of a List. Because it exists, I can create a class that wraps an array as a List with very little code, viz:public final class ArrayAsList<T>()
       extends AbstractList<T>
       private final T[] values;
       public ArrayAsList(T... values) {
          this.values = values;
       @Override
       public T get(int index) {
          return values[index];
       @Override
       public T set(int index, T element) {
          T value = get(index);
          values[index] = element;
          return value;
       @Override
       public int size() {
          return values.length;
    };and somewhere else, I can use it:   List<String> letters =
          new ArrayAsList<String>("a", "b", "c");or perhaps, more practically:   List<String> words = new ArrayAsList<String>(
          bigTextString.split(" +") );Now that may not seem like a big deal to you, but given all that Lists can do, it's actually a very powerful bit of code. The above example is from "Effective Java" (p.95).
    HIH
    Winston

  • Instance of Abstract class

    Hello friends
    I know that abstract class cannot be instanciated but then I really wonder how Calendar class gets instanciated..
    Calendar class is a abstract class but it has a method getInstance().
    How it might have been done in Calendar class when it is abstract ?
    Can anyone help ?
    Thanks and Regads
    Rohit.

    Yepp -:) Through the use of anonymous innerclasses
    you can indirectly instantiate abstract classesand
    interfaces. Basically you create a concrete classwith
    no name but of the abstract class type orinterface type.
    That creates an instance of the concrete sub-class,
    not the abstract class.This is exactly what both I and the OP said. Is it
    only valid when you say it?It's also what I said with a post that started with "Nope...". It sounded like you were disagreeing with me when you said "Yepp....".

  • A question about Abstract Classes

    Hello
    Can someone please help me with the following question.
    Going through Brian's tutorials he defines in one of his exercises an  'abstract' class as follows
    <ClassType ID="MyMP.MyComputerRoleBase" Base="Windows!Microsoft.Windows.ComputerRole" Accessibility="Internal" Abstract="true" Hosted="true" Singleton="false">
    Now I am new to authoring but get the general concepts, and on the surface of it, it appears odd to have an 'abstract' class that is also 'hosted' I understand and abstract class to be a template with one or more properties defined which is then used
    as the base class for one or more concrete classes. Therefore you do not have to keep defining the properties on these concrete classes over and over as they inherit the properties from their parent abstract class, is this correct so far?
    if the above is correct then it seems odd that the abstract class would be hosted, unless (and this is the only way it makes sense to me) that ultimately (apart from singleton classes) any class that is going to end up being discovered and
    thereby an instance of said class instigated in the database must ultimately be hosted somewhere, is that correct?
    in other words if you has an abstract class, which acts as the base class for one or more concrete classes (by which I mean ones for which you are going to create lets say WMI discoveries ), if this parent abstract class is not ultimately
    hosted to a concrete class of its own then these child concrete classes (once discovered) will never actually create instances in the database.
    Is that how it is?
    Any advise most welcome, thanks
    AAnotherUser__
    AAnotherUser__

    Hi,
    Hosting is the only relationship type that doesn't require you to discover it with a discovery rule. OpsMgr will create a relationship instance automatically for you using a 'hosted' properties 'chain' in a class\model definition. In an abstract class definition
    you need to have this property set to 'true' or you will 'brake' a hosting 'chain'.
    http://OpsMgr.ru/

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

  • Getting an abstract class working

    Simply put, something is going wrong with my abstract class, now my assignArray method wont work and my frame wont compile at all anymore.
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    public abstract class bankPresentation extends JFrame implements ActionListener {
         //define the frame properties
         private static final int FRAME_WIDTH = 300;
         private static final int FRAME_HEIGHT = 600;
         private static final int FRAME_X_ORIGIN = 150;
         private static final int FRAME_Y_ORIGIN = 250;
         private static final int BUTTON_WIDTH = 80;
         private static final int BUTTON_HEIGHT = 30;
         //define all the frame elements
         JRadioButton depositRadioButton = new JRadioButton("Deposit");
         JRadioButton withdrawRadioButton = new JRadioButton("Withdraw");
         ButtonGroup bankButtonGroup = new ButtonGroup();
         JLabel amountLabel;
         JTextField amountField;
         JTextArea textArea;
         JScrollPane textBoxScroll;
         JButton newAccountButton;
         JButton summaryButton;
         JButton depositWithdrawButton;
         double initialAmountDouble;
         DecimalFormat formatDecimal = new DecimalFormat("$0.00");
         //create a new array, size is 10
         bankSummary customerList[] = new bankSummary[10];
         public static void main(String[] args) {
              bankPresentation frame = new bankPresentation();
              frame.setVisible(true);
         public bankPresentation() {
              Container contentPane;
              //create the deposit and withdraw radio buttons, put them in a group
              //and add them to the frame
              bankButtonGroup.add(depositRadioButton);
              bankButtonGroup.add(withdrawRadioButton);
              setSize(FRAME_WIDTH, FRAME_HEIGHT);
              setResizable(false);
              setTitle("Ch13 Project");
              setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
              contentPane = getContentPane();
              contentPane.setLayout(new FlowLayout());
              contentPane.add(withdrawRadioButton);
              contentPane.add(depositRadioButton);
              //add a large text area to the pane
              textArea = new JTextArea();
              textArea.setColumns(25);
              textArea.setRows(20);
              textArea.setLineWrap(true);
              textBoxScroll = new JScrollPane(textArea);
              textBoxScroll
                        .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              textArea.setBorder(BorderFactory.createLineBorder(Color.RED));
              // Set to non edit
              textArea.setEditable(false);
              contentPane.add(textBoxScroll);
              //create new buttons to create accounts, deposit/withdraw with existing ones, and
              //get a statement with existing ones
              newAccountButton = new JButton("Create Account");
              newAccountButton.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
              contentPane.add(newAccountButton);
              summaryButton = new JButton("Summary");
              summaryButton.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
              contentPane.add(summaryButton);
              depositWithdrawButton = new JButton("Deposit/Withdraw");
              depositWithdrawButton.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
              contentPane.add(depositWithdrawButton);
              //add actionlisteners to all buttons
              summaryButton.addActionListener(this);
              newAccountButton.addActionListener(this);
              depositRadioButton.addActionListener(this);
              withdrawRadioButton.addActionListener(this);
              depositWithdrawButton.addActionListener(this);
              //initialize the array with some existing accounts
              assignArray();
          abstract void assignArray() {
              for (int i = 0; i < customerList.length; i++) {
                   customerList[i] = new bankSummary();
              customerList[0].setValues("Bob", "Ghost", "1234", "Savings", 500);
              customerList[1].setValues("Joe", "Shmo", "1333", "Checking", 600);
              customerList[2].setValues("Jack", "Biggs", "9023", "Savings", 200);
         public void actionPerformed(ActionEvent event) {
              int arrayIndexInt = 3;
              // Determine source of event
              Object sourceObject = event.getSource();
              //if a new account is created, ask for first name, last name, pin number, and whether it
              //be a checking or savings account, and the initial amount you're depositing
              if (sourceObject == newAccountButton) {
                   String fNameString = JOptionPane.showInputDialog("First Name: ");
                   String lNameString = JOptionPane.showInputDialog("Last Name: ");
                   String pinString = JOptionPane
                             .showInputDialog("Desired Pin Number: ");
                   String accountType = JOptionPane
                             .showInputDialog("Checking or Savings Account? Enter (Checking or Savings)");
                   String initialAmountStr = JOptionPane
                             .showInputDialog("Initial Deposit Amount: ");
                   double initialAmountDouble = Double.parseDouble(initialAmountStr);
                   customerList[arrayIndexInt].setValues(fNameString, lNameString,
                             pinString, accountType, initialAmountDouble);
                   arrayIndexInt += 1;
                   JOptionPane.showMessageDialog(null, "Account Created!");
              //if the summary button is pressed, ask for the first name on the account
              //then ask for the pin, display the balance for that said account
              if (sourceObject == summaryButton) {
                   String nameVerifyStr = JOptionPane
                             .showInputDialog("Firstname on Account: ");
                   String pinVerifyStr = JOptionPane.showInputDialog("Pin Number: ");
                   if (nameVerifyStr.equals(customerList[0].getFirstName())
                             && pinVerifyStr.equals(customerList[0].getPin())) {
                        textArea.append("Customer: " + customerList[0].getFirstName()
                                  + " " + customerList[0].getLastName() + "\nAccount: "
                                  + customerList[0].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[0].getBalance()));
                   if (nameVerifyStr.equals(customerList[1].getFirstName())
                             && pinVerifyStr.equals(customerList[1].getPin())) {
                        textArea.append("Customer: " + customerList[1].getFirstName()
                                  + " " + customerList[1].getLastName() + "\nAccount: "
                                  + customerList[1].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[1].getBalance()));
                   if (nameVerifyStr.equals(customerList[2].getFirstName())
                             && pinVerifyStr.equals(customerList[2].getPin())) {
                        textArea.append("Customer: " + customerList[2].getFirstName()
                                  + " " + customerList[2].getLastName() + "\nAccount: "
                                  + customerList[2].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[2].getBalance()));
                   if (nameVerifyStr.equals(customerList[3].getFirstName())
                             && pinVerifyStr.equals(customerList[3].getPin())) {
                        textArea.append("Customer: " + customerList[3].getFirstName()
                                  + " " + customerList[3].getLastName() + "\nAccount: "
                                  + customerList[3].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[3].getBalance()));
                   if (nameVerifyStr.equals(customerList[4].getFirstName())
                             && pinVerifyStr.equals(customerList[4].getPin())) {
                        textArea.append("\nCustomer: " + customerList[4].getFirstName()
                                  + " " + customerList[4].getLastName() + "\nAccount: "
                                  + customerList[4].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[4].getBalance()));
                   if (nameVerifyStr.equals(customerList[5].getFirstName())
                             && pinVerifyStr.equals(customerList[5].getPin())) {
                        textArea.append("\nCustomer: " + customerList[5].getFirstName()
                                  + " " + customerList[5].getLastName() + "\nAccount: "
                                  + customerList[5].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[5].getBalance()));
                   if (nameVerifyStr.equals(customerList[6].getFirstName())
                             && pinVerifyStr.equals(customerList[6].getPin())) {
                        textArea.append("\nCustomer: " + customerList[6].getFirstName()
                                  + " " + customerList[6].getLastName() + "\nAccount: "
                                  + customerList[6].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[6].getBalance()));
                   if (nameVerifyStr.equals(customerList[7].getFirstName())
                             && pinVerifyStr.equals(customerList[7].getPin())) {
                        textArea.append("\nCustomer: " + customerList[7].getFirstName()
                                  + " " + customerList[7].getLastName() + "\nAccount: "
                                  + customerList[7].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[7].getBalance()));
                   if (nameVerifyStr.equals(customerList[8].getFirstName())
                             && pinVerifyStr.equals(customerList[8].getPin())) {
                        textArea.append("\nCustomer: " + customerList[8].getFirstName()
                                  + " " + customerList[8].getLastName() + "\nAccount: "
                                  + customerList[8].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[8].getBalance()));
                   if (nameVerifyStr.equals(customerList[9].getFirstName())
                             && pinVerifyStr.equals(customerList[9].getPin())) {
                        textArea.append("\nCustomer: " + customerList[9].getFirstName()
                                  + " " + customerList[9].getLastName() + "\nAccount: "
                                  + customerList[9].getAccountType() + "\nBalance: "
                                  + formatDecimal.format(customerList[9].getBalance()));
                   textArea.append("\n===========================");
              //if the deposit/withdraw button is pressed, ask how much to deposit or withdraw
              //depending on which radio button is selected
              //Verify the name and pin on the account
              if (sourceObject == depositWithdrawButton) {
                   String nameVerifyStr = JOptionPane
                             .showInputDialog("Firstname on Account: ");
                   String pinVerifyStr = JOptionPane.showInputDialog("Pin Number: ");
                   if (depositRadioButton.isSelected()) {
                        String depositAmountStr = JOptionPane
                                  .showInputDialog("Deposit Amount: ");
                        double depositAmountDouble = Double
                                  .parseDouble(depositAmountStr);
                        if (nameVerifyStr.equals(customerList[0].getFirstName())
                                  && pinVerifyStr.equals(customerList[0].getPin())) {
                             double balanceDouble = customerList[0].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[0].setValues(customerList[0].getFirstName(),
                                       customerList[0].getLastName(), customerList[0]
                                                 .getPin(),
                                       customerList[0].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[0].getFirstName() + " "
                                       + customerList[0].getLastName() + "\nAccount: "
                                       + customerList[0].getAccountType() + "\nPin: "
                                       + customerList[0].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[1].getFirstName())
                                  && pinVerifyStr.equals(customerList[1].getPin())) {
                             double balanceDouble = customerList[1].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[1].setValues(customerList[1].getFirstName(),
                                       customerList[1].getLastName(), customerList[1]
                                                 .getPin(),
                                       customerList[1].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[1].getFirstName() + " "
                                       + customerList[1].getLastName() + "\nAccount: "
                                       + customerList[1].getAccountType() + "\nPin: "
                                       + customerList[1].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[2].getFirstName())
                                  && pinVerifyStr.equals(customerList[2].getPin())) {
                             double balanceDouble = customerList[2].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[2].setValues(customerList[2].getFirstName(),
                                       customerList[2].getLastName(), customerList[2]
                                                 .getPin(),
                                       customerList[2].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[2].getFirstName() + " "
                                       + customerList[2].getLastName() + "\nAccount: "
                                       + customerList[2].getAccountType() + "\nPin: "
                                       + customerList[2].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[3].getFirstName())
                                  && pinVerifyStr.equals(customerList[3].getPin())) {
                             double balanceDouble = customerList[3].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[3].setValues(customerList[3].getFirstName(),
                                       customerList[3].getLastName(), customerList[3]
                                                 .getPin(),
                                       customerList[3].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[3].getFirstName() + " "
                                       + customerList[3].getLastName() + "\nAccount: "
                                       + customerList[3].getAccountType() + "\nPin: "
                                       + customerList[3].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[4].getFirstName())
                                  && pinVerifyStr.equals(customerList[4].getPin())) {
                             double balanceDouble = customerList[4].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[4].setValues(customerList[4].getFirstName(),
                                       customerList[4].getLastName(), customerList[4]
                                                 .getPin(),
                                       customerList[4].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[4].getFirstName() + " "
                                       + customerList[4].getLastName() + "\nAccount: "
                                       + customerList[4].getAccountType() + "\nPin: "
                                       + customerList[4].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[5].getFirstName())
                                  && pinVerifyStr.equals(customerList[5].getPin())) {
                             double balanceDouble = customerList[5].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[5].setValues(customerList[5].getFirstName(),
                                       customerList[5].getLastName(), customerList[5]
                                                 .getPin(),
                                       customerList[5].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[5].getFirstName() + " "
                                       + customerList[5].getLastName() + "\nAccount: "
                                       + customerList[5].getAccountType() + "\nPin: "
                                       + customerList[5].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[6].getFirstName())
                                  && pinVerifyStr.equals(customerList[6].getPin())) {
                             double balanceDouble = customerList[6].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[6].setValues(customerList[6].getFirstName(),
                                       customerList[6].getLastName(), customerList[6]
                                                 .getPin(),
                                       customerList[6].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[6].getFirstName() + " "
                                       + customerList[6].getLastName() + "\nAccount: "
                                       + customerList[6].getAccountType() + "\nPin: "
                                       + customerList[6].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[7].getFirstName())
                                  && pinVerifyStr.equals(customerList[7].getPin())) {
                             double balanceDouble = customerList[7].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[7].setValues(customerList[7].getFirstName(),
                                       customerList[7].getLastName(), customerList[7]
                                                 .getPin(),
                                       customerList[7].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[7].getFirstName() + " "
                                       + customerList[7].getLastName() + "\nAccount: "
                                       + customerList[7].getAccountType() + "\nPin: "
                                       + customerList[7].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[8].getFirstName())
                                  && pinVerifyStr.equals(customerList[8].getPin())) {
                             double balanceDouble = customerList[8].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[8].setValues(customerList[8].getFirstName(),
                                       customerList[8].getLastName(), customerList[8]
                                                 .getPin(),
                                       customerList[8].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[8].getFirstName() + " "
                                       + customerList[8].getLastName() + "\nAccount: "
                                       + customerList[8].getAccountType() + "\nPin: "
                                       + customerList[8].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[9].getFirstName())
                                  && pinVerifyStr.equals(customerList[9].getPin())) {
                             double balanceDouble = customerList[9].getBalance();
                             balanceDouble += depositAmountDouble;
                             customerList[9].setValues(customerList[9].getFirstName(),
                                       customerList[9].getLastName(), customerList[9]
                                                 .getPin(),
                                       customerList[9].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[9].getFirstName() + " "
                                       + customerList[9].getLastName() + "\nAccount: "
                                       + customerList[9].getAccountType() + "\nPin: "
                                       + customerList[9].getPin() + "\nChanges: +"
                                       + depositAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                   if (withdrawRadioButton.isSelected()) {
                        String withdrawAmountStr = JOptionPane
                                  .showInputDialog("Withdraw Amount: ");
                        double withdrawAmountDouble = Double
                                  .parseDouble(withdrawAmountStr);
                        double chargeDouble;
                        if (withdrawAmountDouble > 2000) {
                             chargeDouble = 0.75;
                        } else if (withdrawAmountDouble > 750) {
                             chargeDouble = 0.50;
                        } else {
                             chargeDouble = 0;
                        if (nameVerifyStr.equals(customerList[0].getFirstName())
                                  && pinVerifyStr.equals(customerList[0].getPin())) {
                             double balanceDouble = customerList[0].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[0].setValues(customerList[0].getFirstName(),
                                       customerList[0].getLastName(), customerList[0]
                                                 .getPin(),
                                       customerList[0].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[0].getFirstName() + " "
                                       + customerList[0].getLastName() + "\nAccount: "
                                       + customerList[0].getAccountType() + "\nPin: "
                                       + customerList[0].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[1].getFirstName())
                                  && pinVerifyStr.equals(customerList[1].getPin())) {
                             double balanceDouble = customerList[1].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[1].setValues(customerList[1].getFirstName(),
                                       customerList[1].getLastName(), customerList[1]
                                                 .getPin(),
                                       customerList[1].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[1].getFirstName() + " "
                                       + customerList[1].getLastName() + "\nAccount: "
                                       + customerList[1].getAccountType() + "\nPin: "
                                       + customerList[1].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[2].getFirstName())
                                  && pinVerifyStr.equals(customerList[2].getPin())) {
                             double balanceDouble = customerList[2].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[2].setValues(customerList[2].getFirstName(),
                                       customerList[2].getLastName(), customerList[2]
                                                 .getPin(),
                                       customerList[2].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[2].getFirstName() + " "
                                       + customerList[2].getLastName() + "\nAccount: "
                                       + customerList[2].getAccountType() + "\nPin: "
                                       + customerList[2].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[3].getFirstName())
                                  && pinVerifyStr.equals(customerList[3].getPin())) {
                             double balanceDouble = customerList[3].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[3].setValues(customerList[3].getFirstName(),
                                       customerList[3].getLastName(), customerList[3]
                                                 .getPin(),
                                       customerList[3].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[3].getFirstName() + " "
                                       + customerList[3].getLastName() + "\nAccount: "
                                       + customerList[3].getAccountType() + "\nPin: "
                                       + customerList[3].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[4].getFirstName())
                                  && pinVerifyStr.equals(customerList[4].getPin())) {
                             double balanceDouble = customerList[4].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[4].setValues(customerList[4].getFirstName(),
                                       customerList[4].getLastName(), customerList[4]
                                                 .getPin(),
                                       customerList[4].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[4].getFirstName() + " "
                                       + customerList[4].getLastName() + "\nAccount: "
                                       + customerList[4].getAccountType() + "\nPin: "
                                       + customerList[4].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[5].getFirstName())
                                  && pinVerifyStr.equals(customerList[5].getPin())) {
                             double balanceDouble = customerList[5].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[5].setValues(customerList[5].getFirstName(),
                                       customerList[5].getLastName(), customerList[5]
                                                 .getPin(),
                                       customerList[5].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[5].getFirstName() + " "
                                       + customerList[5].getLastName() + "\nAccount: "
                                       + customerList[5].getAccountType() + "\nPin: "
                                       + customerList[5].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[6].getFirstName())
                                  && pinVerifyStr.equals(customerList[6].getPin())) {
                             double balanceDouble = customerList[6].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[6].setValues(customerList[6].getFirstName(),
                                       customerList[6].getLastName(), customerList[6]
                                                 .getPin(),
                                       customerList[6].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[6].getFirstName() + " "
                                       + customerList[6].getLastName() + "\nAccount: "
                                       + customerList[6].getAccountType() + "\nPin: "
                                       + customerList[6].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[7].getFirstName())
                                  && pinVerifyStr.equals(customerList[7].getPin())) {
                             double balanceDouble = customerList[7].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[7].setValues(customerList[7].getFirstName(),
                                       customerList[7].getLastName(), customerList[7]
                                                 .getPin(),
                                       customerList[7].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[7].getFirstName() + " "
                                       + customerList[7].getLastName() + "\nAccount: "
                                       + customerList[7].getAccountType() + "\nPin: "
                                       + customerList[7].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[8].getFirstName())
                                  && pinVerifyStr.equals(customerList[8].getPin())) {
                             double balanceDouble = customerList[8].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[8].setValues(customerList[8].getFirstName(),
                                       customerList[8].getLastName(), customerList[8]
                                                 .getPin(),
                                       customerList[8].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[8].getFirstName() + " "
                                       + customerList[8].getLastName() + "\nAccount: "
                                       + customerList[8].getAccountType() + "\nPin: "
                                       + customerList[8].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
                        if (nameVerifyStr.equals(customerList[9].getFirstName())
                                  && pinVerifyStr.equals(customerList[9].getPin())) {
                             double balanceDouble = customerList[9].getBalance();
                             if (withdrawAmountDouble + chargeDouble > balanceDouble) {
                                  JOptionPane.showMessageDialog(null,
                                            "Withdraw Exceeds Balance!");
                             } else {
                                  balanceDouble -= (withdrawAmountDouble + chargeDouble);
                             customerList[9].setValues(customerList[9].getFirstName(),
                                       customerList[9].getLastName(), customerList[9]
                                                 .getPin(),
                                       customerList[9].getAccountType(), balanceDouble);
                             textArea.append("\nCustomer: "
                                       + customerList[9].getFirstName() + " "
                                       + customerList[9].getLastName() + "\nAccount: "
                                       + customerList[9].getAccountType() + "\nPin: "
                                       + customerList[9].getPin() + "\nChanges: -"
                                       + withdrawAmountDouble + "\nBalance: "
                                       + formatDecimal.format(balanceDouble));
    }Any suggestions would be much appreciated
    - Thanks - GoOsE

    (1) thanks for the wall of code.
    (2) thanks for providing readers with the compilation errors.
    (3) why are you using camelcase for Class names?
    [*READ THIS*|http://mindprod.com/jgloss/abstract.html]
    the errors seem very straight forward to me:
    bankPresentation.java:34: cannot find symbol
    symbol : class bankSummary
    location: class bankPresentation
         bankSummary customerList[] = new bankSummary[10];
         ^
    bankPresentation.java:34: cannot find symbol
    symbol : class bankSummary
    location: class bankPresentation
         bankSummary customerList[] = new bankSummary[10];
         ^
    bankPresentation.java:38: bankPresentation is abstract; cannot be instantiated
              bankPresentation frame = new bankPresentation();
              ^
    bankPresentation.java:103: abstract methods cannot have a body <---- PAY ATTENTION
         abstract void assignArray() {
         ^
    4 errors
    Tool completed with exit code 1

  • Abstract Classes versus Interfaces

    Somebody at work has just made an interesting observation and its bugging me, comments please.
    When I started Java I just used classes (and abstract classes), and didnt bother with Interfaces I understood them to be a way of getting round the lack of MultipleInheritance and it wasnt a problem that concerned me.
    But as time went on I found that sometimes I did want classes that had little in common to provide some additional feature (such as logging), and interfaces were great for this.
    ..so I was happy ..
    During all this time if I want a HashSet I would write code like this
    HashSet dataSet = new HashSet();but then I read that HashSet was an implementation detail and we should be using Interfaces as follows:
    Set dataSet = new HashSet();So whereas before I might have had a class hierachy with an Abstract class at the top , I started slotting in Interfaces above that and viewing the Abstract class as just a convenience to implementing the Interface.
    So which is the right method , originally I saw subclassing object as an 'is a ' relationship and implementing an interface as a 'implements' relationship. But more recently it seems to be turned on its head and implementing an interface is an 'is a' relationship (but supports multiple inheritance)
    Also it seems to be the trouble with this second approach is that anyone can implement an interface, for example I could implement Set,Map and List with one class, the class hierachy is not so helpful .

    Thanks, but the question was alot wider than that,
    the HashSet example was just one part of it.I think it is representative of all the situations that you talk about, which are whether an instantiator should handle the instantiated object by its interface or by its implementation.
    I suppose the question is
    "How do you code model "is a " relationship in java
    through extending a class or creating an interface
    and implementing it"
    MySubClass extends MySuperClass implements MyInterface {}MySubClass is a MySuperClass and a MyInterface. The way that I view it, the "is a" relationship applies to all type inheritance, even for the multiple type inheritance that you can have with interfaces. The "is a" relationship doesn't doesn't have to be a 1:1 mapping. There's no point in thinking about it differently since that's how the language behaves.
    an alternative question is
    "is it correct to mix/match both methods I described
    above"I thought I gave an answer. You said that my answer is not "broad enough." How so? My answer was that handling an object that you instantiate by its interface can reduce the amount of changes you have to make if you change the implementation. You will have to make one change (the line of code that instantiates the object) instead of many. Also, handling it by its interface makes it easier to switch from object A instantiating object B to object A being passed a reference to B and to object A getting its dependencies injected by XML configuration.
    It seems weird to handle an object by its interface if you already know it's implementation, but it's commonly seen and this is why I think it must be used. As I said, it's a small benefit of abstraction.
    The times when you may not want to do this is when the instantiator has to call methods from different interfaces of the object. You can handle it by its interface by casting between the different interfaces you have to work with, or you can just handle it by its implementation, gaining access to all of the object's interfaces.
    Note that everything I explained concerns the type by which the instantiator handles an instantiated object. If a class does not instantiate a certain object, then it almost always should receive it by its interface, unless it's some really common implementation that's never going to change.
    I use interface, abstract class, and base class interchangeably. It's up to you to decide which to use for type inheritance. It's good practice to favor interfaces.

  • Abstract Class and Constructors

    Why is it that Constructors are permitted within an abstract class?

    But how is it possible to create/instantiate Abstract
    classes?It's not. The only class that gets instantiated is the concrete child class.
    As somebody already said, invoking a constructor does NOT create the object.
    When you do new Foo(), the constructor does NOT instantiate the Foo. The new operator does. It allocates the memory, sets default values for member variables, and then it invokes the constructor. If that ctor invokes a chain of other ctors in itself and its parent, and so on up the chain, you're NOT creating more and more objects. You're just running additional constructors on the one object that has already been created.
    What is the use of a constructor in an abstract class?Just like in any other class: to initialize fields.

  • Mixing polymorphism with abstract classes???

    Hi,
    Can you have polymorhism with abstract superclasses in Java?
    For example, say I have a superclass called Pet:
    abstract class Pet {
         private String name;
         public String getName() {
              return name;
        public void setName(String petName) {
             name = petName;
        public String speak() {
             return "I am a Pet";
    }Now I have a Cat subclass:
    public class Cat extends Pet{
        public String speak {
             return "i am a cat";
    public class Dog extends Pet {
    public String fetch() {
         return "fetching a stick";
    }In my test method I have:
    public class TestPet {
         public static void main(String[] args) {
              Pet p = new Pet();
              System.out.println(p.speak());
              Pet p = new Dog();
              System.out.println(((Dog)p).fetch());
              Pet p = new Cat();
              System.out.println(p.speak() +" is now a cat");
    }So it appears to me that you cannot have polymorphic methods with an abstract superclass - is this right?
    Cheers.

    cotton.m wrote:
    List<Pet> pets = new ArrayList<Pet>();
    I was working (more or less) along the same lines...
    package forums;
    import java.util.List;
    import java.util.ArrayList;
    abstract class Pet
      private String name;
      public String getName() { return this.name; }
      public void setName(String name) { this.name = name; }
      public String speak() {
        return "I am a Pet";
      public abstract String fetch(); // <<<<< the new bit.
      public String getClassName() {
        final String name = this.getClass().getName();
        return name.substring(name.lastIndexOf('.')+1).toLowerCase();
    class Cat extends Pet
      public Cat(String name) {
        setName(name);
      public String speak() {
        return "I am a cat";
      public String fetch() {
        return "No. I am a cat!";
      public String rollOver() {
        return "No. I am a cat!";
    class Dog extends Pet
      public Dog(String name) {
        setName(name);
      public String fetch() {
        return "Look boss, I'm fetching the stick.";
      public String sit() {
        return "Look boss, I'm sitting!";
    public class PetTest
      public static void main(String[] args) {
        List<Pet> pets = new ArrayList<Pet>();
        pets.add(new Cat("Fungus"));
        pets.add(new Dog("Spike"));
        for ( Pet pet : pets ) {
          System.out.println("\""+pet.speak()+"\" said "+pet.getName()+" the "+pet.getClassName()+".");
          System.out.println("\"Go fetch\" said the master.");
          System.out.println("\""+pet.fetch()+"\" said "+pet.getName()+".");
          System.out.println();
        System.out.println("Therefore we conclude that dogs are much better pets.");
    }Both these examples demonstrate that polymorphism is very useful when we have a list of different-type-if-things which have a common interface... i.e. different classes which have (a) a common ancestor; or (b) a common interface... allowing us to treat those different types-of-things as if they where one-type-of-thing, except the-different-types actually do different stuff internally, which is appropriate-to-there-specific-type.
    That's the essence of polymorphism... and, of course, this seperation of "type" and "implementation" isn't limited to lists-of-stuff... it can be very useful all over the show.
    Cheers. Keith.
    Edited by: corlettk on 10/05/2009 11:01 ~~ That's a bit clearer.

  • A qestion about abstract class

    Dear friends!
    I have follow simple code:
    abstract class Aclass {
    abstract void method1();     
    class Bclass extends Aclass {
    public void method1(String s){
    // implementation
    As I understand I can overload the method "method1" but I got an error.
    So what should I do?
    Thanks

    As I understand I can overload the method "method1"
    but I got an error.
    So what should I do?First of all, whenever you are getting an error and you ask a question here about that error, you should tell us what the error is - most of the tim, you won't get a useful answer if we have to guess what your problem is. Also, when posting code, please use the forum's [code]...[[b]code] formatting tags (see the "special tokens" link when posting a message - you are much more likely to get a useful response if we can read your code - many people will just ignore your question if it is not easy to read.
    Having said that, I'll hazard a guess that the error you are getting is somewhere along the lines of "Class Bclass must implement the inherited abstract method method1()". If so, then that is what you should do - implement amethod called method1 in class Bclass, that takes no arguments.
    Yes, you can overload method1, but you have then implemented an entirely different method - you must supply a no-args version as well.

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

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

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

  • 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

Maybe you are looking for