Problems implementing abstract classes

hello.
this is james mcfadden. I am developing a multiplayer BlackJack card game in Java. the game consists of three programs: BlackJack.java, BlackJackServer.java and BlackJackClient.java (three 3 programs are shown below). i don't know how to implement abstract classes. i am trying to get the BlackJack.java program working with the BlackJackServer.java program. there should be "extends BlackJackServer" somewhere in the BlackJack.java program, but i don't know where.
import javax.swing.*;
public class BlackJack extends JPanel{
   public BlackJack(){
      //FlowLayout is default layout manager for a JPanel
      add(new JButton("Hit"));
      add(new JButton("Stay"));
      add(new JButton("New Game"));
   public static void main(String[] args){
      JFrame frame=new JFrame("BlackJack");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(500,500);
      frame.setLocation(200,200);
      BlackJack bj=new BlackJack();
      frame.setContentPane(bj);
      frame.setVisible(true);
import java.io.*;//Provides for system input and output through data streams, serialization and the file system
import java.net.*;//Provides the classes for implementing networking applications
import java.util.*;//Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes
import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
public class BlackJackServer extends JFrame{
   private JTextArea jta=new JTextArea();//a text area for displaying text
   public static void main(String[] args){  
          new BlackJackServer();//invokes the constructor BlackJackServer()
   }//end main
   public BlackJackServer(){
      setLayout(new BorderLayout());//places the text area on the frame
      add(new JScrollPane(jta),BorderLayout.CENTER);//lays out a text area, arranging and resizing its components to fit in the centre region;and provides a scrollable view of a lightweight component
      setTitle("BlackJack Server");//Sets the title for this frame to the specified string
      setSize(500,300);//Resizes this component so that it has a width and a height
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Sets the operation that will happen by default when the user closes this frame
      setVisible(true);//shows the frame
      try{
         ServerSocket serverSocket=new ServerSocket(8000);//creates a server socket
         jta.append("Server started at "+new Date()+'\n');//displays the current date in the text area
         Socket socket=serverSocket.accept();//listens for a connection request
         DataInputStream inputFromClient=new DataInputStream(socket.getInputStream());//creates a data input stream
         DataOutputStream outputToClient=new DataOutputStream(socket.getOutputStream());//creates a data output stream
         while(true){
            float bet=inputFromClient.readFloat();//receives bet from the client
            float doublebet=bet+bet;//computes double the bet
            outputToClient.writeFloat(doublebet);//sends double the bet back to the client
            jta.append("Bet received from client: "+bet+'\n');//displays the bet in the text area
            jta.append("Double the bet found: "+doublebet+'\n');//displays double the bet in the text area
         }//end while
      }//end try
      catch(IOException ex){
         System.err.println(ex);//displays an error message
      }//end catch
   }//end constructor
}//end class BlackJackServer
import java.io.*;//Provides for system input and output through data streams, serialization and the file system
import java.net.*;//Provides the classes for implementing networking applications
import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
public class BlackJackClient extends JFrame{
   private JTextField jtf=new JTextField();//a text field for receiving text
   private JTextArea jta=new JTextArea();//a text area for displaying text
   private DataOutputStream toServer;//output stream
   private DataInputStream fromServer;//input stream
   public static void main(String[] args){
      new BlackJackClient();//invokes the constructor BlackJackClient()
   public BlackJackClient(){
      JPanel p=new JPanel();//holds the label and text field
      p.setLayout(new BorderLayout());//sets the layout of the content pane of this component by default
      p.add(new JLabel("Enter bet"),BorderLayout.WEST);//displays the bet and lays out a JLabel, arranging and resizing its components to fit in the western region
      p.add(jtf,BorderLayout.CENTER);//lays out the text field, arranging and resizing its components to fit in the centre region
      jtf.setHorizontalAlignment(JTextField.RIGHT);//Sets the horizontal alignment of the text to the right
      setLayout(new BorderLayout());//places the text area on the frame
      add(p,BorderLayout.NORTH);//lays out the text field, arranging and resizing its components to fit in the northern region
      add(new JScrollPane(jta),BorderLayout.CENTER);//lays out a text area, arranging and resizing its components to fit in the centre region;and provides a scrollable view of a lightweight component
      jtf.addActionListener(new ButtonListener());//invokes the ButtonListener class
      setTitle("BlackJack Client");//Sets the title for this frame to the specified string
      setSize(500,300);//Resizes this component so that it has a width and a height
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Sets the operation that will happen by default when the user closes this frame
      setVisible(true);//shows the frame
      try{
         Socket socket=new Socket("localhost",8000);//creates a socket to connect to the server
         fromServer=new DataInputStream(socket.getInputStream());//creates an input stream to receive data from the server
         toServer=new DataOutputStream(socket.getOutputStream());//creates an output stream to send data to the server
      }//end try
      catch(IOException ex){
         jta.append(ex.toString()+'\n');//displays an error message
      }//end catch
   private class ButtonListener implements ActionListener{
      public void actionPerformed(ActionEvent e){
         try{
            float bet=Float.parseFloat(jtf.getText().trim());//gets the bet from the text field
            toServer.writeFloat(bet);//Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream
            toServer.flush();//Flushes this output stream and forces any buffered output bytes to be written out
            float doublebet=fromServer.readFloat();//gets double the bet from the server
            jta.append("Bet is "+bet+"\n");//displays the bet in the text area
            jta.append("Double the bet received from the server is "+doublebet+'\n');//displays double the bet in the text area
         }//end try
         catch(IOException ex){
            System.err.println(ex);//displays an error message
         }//end catch
      }//end method
   }//end class
}//end class BlackJackClient

there should be "extends BlackJackServer" somewhere in the BlackJack.java programI very much doubt that.
It's possible you might need to create a BlackJackServer object or something like that. But I don't see the point in subclassing it.

Similar Messages

  • Problem compiling Abstract class

    Hi
    I have writting an abstract class Sort.java and another class BubbleSort.java. I am having problems compiling BubbleSort.java class.
    The following is the error message
    BubbleSort.java:8: missing method body, or declare abstract
         public int doSorting(int[] array);
    ^
    BubbleSort.java:11: return outside method
              return num;
    ^
    The following is the code
    public abstract class Sort
    public abstract int doSorting(int[] array);
    }// End of class
    public class BubbleSort extends Sort
    private int num = 2;
    public int doSorting(int[] array);
    num = num + 2;
    return num;
    } // end of class

    Remove the semi-colon.
    public int doSorting(int[] array); // <------- there

  • Problems with abstract classes

    I'm reading Java Wireless Blueprints and i'm confused with the functionality of abstract classes, especially in the next section:
    public byte[] getPoster() throws ApplicationException {
    if (poster == null) {
    try {
    poster =
    ModelObjectLoader.getInstance().getMoviePoster(primaryKey);
    } catch (ModelException me) {
    throw new ApplicationException();
    return poster;
    This class invoque to the ModelObjectLoader class that is abstract and after invoque getInstance().getMoviePoster(primaryKey); method. The source code of the class is:
    public abstract class ModelObjectLoader {
    private static ModelObjectLoader instance = null;
    protected ModelObjectLoader() {
    instance = this;
    return;
    public static ModelObjectLoader getInstance() {
    return instance;
    public abstract TheaterSchedule getTheaterSchedule(Theater theater)
    throws ModelException, ApplicationException;
    public abstract Movie getMovie(String movieKey)
    throws ModelException, ApplicationException;
    public abstract Movie getMovie(Movie movie)
    throws ModelException, ApplicationException;
    public abstract byte[] getMoviePoster(String movieKey)
    throws ModelException, ApplicationException;
    public abstract int[][] getMovieShowTimes(String theaterKey, String movieKey)
    throws ModelException, ApplicationException;
    public abstract SeatingPlan getSeatingPlan(String theaterKey,
    String movieKey,
    int[] showTime) throws ModelException,
    ApplicationException;
    I don�t find where is the implementation of the getMoviePoster(primaryKey) method.
    Can you help me to understand.
    Thanks

    public abstract byte[] getMoviePoster(String movieKey)It's an abstract method, which means that any concrete class that extends ModelObjectLoader must implement the method. If you really need to know (you might not), then call getInstance() and output the result of getClass().getName() on that object. That will tell you its type, and then you can go look at the source.

  • Concrete classes implement abstract class and implements the interface

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

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

  • Object oriented design problem concerning abstract classes and interfaces

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

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

  • Implemetation of abstract classes (WindowAdapter 4 example)

    Hi,
    Since I migrate form JDev9i beta version to JDev9i v 9.0.2.829 I unable to recompile all the java source wich implement abstract classes.
    an example :
    source code :
    frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    give me this error when i try to compile:
    Error(30,5): class DiscoReader$1 not found in class DiscoReader.DiscoReader
    where DiscoReader is the name of my package and the name of this class in this package.
    Did someone experiment this problem ? and of course, did someone know how to solve it ?
    thanks
    Olivier Ardouin
    mailto:[email protected]

    I believe this problem is already fixed in 9.0.3, shortly available on OTN.
    Thanks for reporting it,
    Michel

  • Inheritance problem with parent class calling child class

    I have a problem with inheritance with a parent class calling a child class method. Below is the example pseudocode code and my problem:
    public abstract class A {
        protected void function1 ( ) { }
        protected void function2 () {
             //calls function1();
             function1();
    public abstract class B extends A {
        protected void function1 ()  {
             // do stuff
    public class C extends B {
        protected void function1 ()  {
            // do stuff
            super.function1 ();
    }I have an object instance of class C created and its function2() is invoked.
    My problem is, while in function2(), which belongs to abstract class A and the method call to function 1() is called, the call invokes the function1() of class B. Shouldn't the call invoke function 1() of class C instead? And then function1() of class B will be called after due to the super.function1(). It's not behaving like I thought it would.
    Edited by: crono77 on Jan 10, 2008 8:13 PM

    Nevermind, i found my error :)

  • Implement abstract method from base class problem

    Here is the example:
    public abstract class AbstractClass{
    protected double aVariable;
    protected abstract double abstractMethod();
    public class RealClass extends AbstractClass{
    public double abstractMethod(){
    return aVariable;
    Error message:
    RealClass should be declared abstract; it does not define abstractMethod() in AbstractClass

    I also compiled the code with Jdk1.3 and it
    worked.. The code would not have compiled
    if the access modifier in the derived class
    was more restrictive(eg private )...

  • Implementing Comparable in an abstract class

    Hi all,
    I am making my first sortie with abstract classes. I have had a good look around, but would still appreciate some advice with the following problem.
    In my application I have several classes that have many things in common. I have concluded therefore, that if I create and then inherit from an abstract super class, I can reduce and improve my code. I created this abstract class:
    public abstract class YAbstractObject implements Comparable {
        public YAbstractObject(int projectId, YObject object, String objectName) {
            this.projectId = projectId; // Always the same parameters
            this.object = object;
            this.objectName = objectName;
        // This is abstract as it must always be present for sub classes but differant processing will take place
        public abstract void resolveObject();
        // These three methods will always be the same for all sub classes
        public String getName() {
            return objectName;
        public YObject getObject() {
            return object;
        public boolean isValid() {
            return isValid;
    // Overridden and always the same for all sub classes
        public String toString() {
            return objectName;
        // implemented abstract method
        public int compareTo(Object thatObject) {
            // Issue here! I would like something as follows:
            //  return this.getName().compareToIgnoreCase(thatObject.getName());
    // Variable decleration
        private int projectId;
        private YObject object;
        private String objectName;
        private boolean isValid;As I have commented in the compareTo() method, I would like it to be able to use the getName() method for comparison objects and compare them. But it does not like this, as it does not know that "thatObject" is of the same class as this object - I hope that made sense.
    in essence, I want to inherit this method for different classes and have it work with each.
    Is there a way to do this? Generics?
    Any observations, greatly appreciated,
    Steve

    You can use also generics (if applicable: java -version >= 1.5).
    public abstract class Test implements Comparable<Test> {
         String name;
         public Test(String name) {
              this.name = name;
         public String getName() {
              return name;
         public int compareTo(Test obj) {
              return this.getName().compareTo(obj.getName());
    public class Other extends Test {
         public Other(String name) {
              super(name);
    public class Tester extends Test {
         public Tester(String name) {
              super(name);
         public static void main(String[] args) {
              Test t = new Tester("t");
              Test a = new Tester("a");
              Test o = new Other("t");
              System.out.println(t.compareTo(a));
              System.out.println(t.compareTo(new Object())); //compile error
              System.out.println(t.compareTo(o));
    }Without the compile error line it will give the following result:
    19
    0

  • Extend abstract class & implement interface, different return type methods

    abstract class X
    public abstract String method();
    interface Y
    public void method();
    class Z extends X implements Y
      // Compiler error, If I don't implement both methods
      // If I implement only one method, compiler error is thrown for not
      // implementing another method
      // If I implement both the methods,duplicate method error is thrown by 
      //compiler
    The same problem can occur if both methods throw different checked exceptions,or if access modifiers are different..etc
    I'm preparing for SCJP, So just had this weired thought. Please let me know
    if there is a way to solve this.

    Nothing you can do about it except for changing the design.
    Kaj

  • Why does this abstract class and method work without implement it?

    hi,
    I have seen many times that in some examples that there are objects made from abstract classes directly. However, in all books, manual and tutorials that I've read explain that we MUST implement those methods in a subclass.
    An example of what I'm saying is the example code here . In a few words that example makes Channels (java.nio.channel) and does operations with them. My problem is in the class to make this channels, because they used the ServerSockeChannel class and socket() method directly despite they are abstracts.
       // Create a new channel: if port == 0, FileChannel on /dev/tty, else
       // a SocketChannel from the first accept on the given port number
    private static ByteChannel newChannel (int netPort)
          throws Exception
          if (netPort == 0) {
             FileInputStream fis = new FileInputStream ("/dev/tty");
             return (fis.getChannel());
          } else {
    //CONFLICT LINES
             ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
             ssc.socket().bind (new InetSocketAddress (netPort)); //<--but here, this method (socket) is abstract. WHY RETURN A SOCKET????????  this mehod should be empty by default.
             System.out.print ("Waiting for connection on port "
                + netPort + "...");
             System.out.flush();
             ByteChannel channel = ssc.accept();
             ssc.close();
             System.out.println ("Got it");
             return (channel);
       } I test this code and works fine. So why can it be??
    Also, I read that the abstract classes can't have static methods. Is it true???
    Please Help!!
    PS: i have seen this kind of code many times. So i feel that I don't understand how its really the abstract methods are made.
    PS2: I understand that obviously you don't do something like this: *"obj = new AbstractClass(); "*. I dont understand how it could be: ServerSocketChannel ssc = ServerSocketChannel.open(); and the compiler didn't warn.

    molavec wrote:
    ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
    The static method creates an instance of a class which extends ServerSocketChannel, but is actually another non-abstract class.I thought that, but reading the documentation I saw that about open() method:
    Opens a server-socket channel.
    The new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.
    The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.
    ...and the problem is the same openServerSocketChannel is abstract, so i don't understand how it could return a ServerSocketChannel.There is a concrete implementation class that has implemented that method.
    I guess that really the open() method use a SelectorProvider's subclase but it doesn't appear in the doc.It doesn't need to. First, you don't care about those implementation details, and second, you know that if the class is abstract, it must use some concrete subclass.
    Ok, I speak Spanish by default (<-- this sounds like "I am a machine", ^_^' ). So, I didn't know how to say that the method would be {}. Is there a way to say that?? I recommendable for me to know, for the future questions o answers.Not sure what you're saying here. But the other respondent was trying to explain to you the difference between an abstract method and an empty method.
    // abstract method
    public abstract void foo();
    // empty method
    public void bar() {
    Which class does extend ServerSocketChannel? I can not see it.It may be a package-private class or a private nested class. There's no need to document that specific implementation, since you never need to use it directly.

  • Implement method inside abstract class?

    hello everyone:
    I have a question regarding implementation of method inside a abstract class. The abstract class has a static method to swamp two numbers.
    The problem ask if there is any output from the program; if no output explain why?
    This is a quiz question I took from a java class. I tried the best to recollect the code sample from my memory.
    if the code segment doesn't make sense, could you list several cases that meet the purpose of the question. I appreciate your help!
    code sample
    public abstract class SwampNumber
       int a = 4;
       int b = 2;
       System.out.println(a);
       System.out.println(b);
       swamp(a, b);
       public static void swamp(int a, int b)
         int temp = a;
             a = b;
             b = a;
         System.out.println(a);
         System.out.println(b);

    It won't compile.
    You can't instantiate an abstract class before you know anything.
    //somewhere in main
    SwampNumber myNum = new SwampNumber();
    //Syntax ErrorQuote DrClap
    This error commonly occurs when you have code that >>is not inside a method.
    The only statements that can appear outside methods >>in a Java class are >>declarations.Message was edited by:
    lethalwire

  • Problems with extension of generic abstract class

    Hello,
    I'm having some problems with the extension of a generic abstract class. The compiler tells me I have not implemented an abstract method but I think I have. I have defined the following interface/class hierarchy:
    public interface Mutator<T extends Individual<S>, S> {
         public void apply( T<S> ind );
    public abstract class AbstractMutator<T extends Individual<S>, S> implements Mutator<T, S> {
         public abstract void apply( T<S> ind );
    }Now I implement AbstractMutator as such:
    public class BinaryMutator extends AbstractMutator<StringIndividual<Integer>, Integer> {
         public void apply( StringIndividual<Integer> ind ) { ... }
    }The compiler says:
    BinaryMutator.java:3: ga.BinaryMutator is not abstract and does not override abstract method apply(ga.Individual<java.lang.Integer>) in ga.AbstractMutator
    Why does it say the signature of the abstract method is apply(Individual<Integer>) if I have typed the superclass as StringIndividual<Integer>?
    Thanks.

    Yes, but the abstract method takes an arg of type <T extends Individual>. So it takes an Individual or a subclass thereof, depending on how I parameterise the class, right? StringIndividual is a subclass of Individual. So if I specify T to be StringIndividual, doesn't the method then take an arg of type StringIndividual?

  • Instance of one of implementations of abstract class depending on context??

    Hi all,
    I just wonder if it is possible in Java to call creation of a new instance of an implementation of an abstract class depending on context.
    I mean something like:
    abstract class Abstract
    //1st implementation of Abstract class
    class Concrete1 extends Abstract
    //2nd implementation of Abstract class
    class Concrete2 extends Abstract
    }And now, somewhere else in the code, I would really need to call something like this:
    Abstract test1 = new ...(); //here I need sometimes to be created instance of Concrete1, sometimes instance of Concrete2
    Is there a way how to do this??

    Some more concrete code if it helps:
    Abstract class:
    * Individual.java
    * Created on 21. leden 2007, 1:08
    package genetics;
    * Abstract class defining fields and methods of one individual for genetic algorithms
    * This class is supposed to be implemented according to problem to be solved
    * @author Richard V�tek
    * @version 1.0
    abstract public class Individual implements Comparable<Individual>
       * Create random chromosomes for this individual
      protected abstract void createRandomChromosomes();
       * Count fitness of this individual
       * This number says how good is this individual (the higher number the better).
       * Better fitness means that this individual is closer to solution.
       * @return  int   Fitness of this individual
      protected abstract int getFitness();
       * Cross-breed this individual with another individual
       * This leaves untouched number of chromosomes to certain (randomly generated) position.
       * From this position on, it will swap chromosomes between this and another individual.
       * So this individual gets changed (cross-breeded) as well as the other, which is returned
       * as result of this method.
       * @param   other              The other individual to cross-breed with
       * @return  Individual         Hybrid of this and another individual (in fact, the other individual
       *                             after cross-breed (this (source) individual gets changed too after cross-breed)
      protected abstract Individual crossbreed(Individual other);
       * Mutate this individual
       * Mutate chromosomes of this individual; every chromosome is mutated
       * with probability set in settings of evolution.
       * This probability is supposed to be quite low number, roughly 1 %.
      protected abstract void mutate();
       * Check this individual
       * Check if this individual still suits the assignment.
       * If not, repair this individual to suit it again.
      protected abstract void check();
       * Implementation of Comparable: comparing of individuals by fitness
       * @param other Another individual to compare
      public int compareTo(Individual other)
        return this.getFitness() - other.getFitness();
    One implementation class:
    * KnapsackIndividual.java
    * Created on 21. leden 2007, 1:41
    package genetics;
    import java.util.Random;
    import java.util.TreeMap;
    import knapsack.KnapsackProblem;
    * This is practically the same as KnapsackProblem class but designed specially
    * for solving knapsack problem with genetic algorithm so all unnecessary fields
    * and methods are removed.
    * @author Richard V�tek
    * @version 1.0
    public class KnapsackIndividual extends Individual
       * Chromosomes of this individual
       * In case of knapsack problem, they are things currentl in knasack
      protected boolean[] arrChromosomes;
       * Cached value of fitness of this individual
       * Used to not to count fitness of this individual everytime when needed
       * (and it is often needed); once counted, it will be read from this cached value
      private int intFitnessCache = Integer.MIN_VALUE;
       * Randomizer for random-driven methods (like mutation, etc.)
      private Random randomizer = new Random();
       * Reference to evolution to read mutation probability from
      protected Evolution evolution;
       * Assignment of problem instance
      protected KnapsackProblem assignment;
       * Create a new Individual instance
       * @param   assignment  Object representing assignment of particular problem
       * @param   evolution   Reference to evolution object to be able to read evolution's settings from
      public KnapsackIndividual(KnapsackProblem assignment, Evolution evolution)
        this.assignment = assignment;
        this.evolution = evolution;
        this.arrChromosomes = new boolean[assignment.getNumberOfThings()];
       * Create random chromosomes for this individual
       * @see Individual#createRandomChromosomes()
      protected void createRandomChromosomes()
        int intChromosomeCount = this.arrChromosomes.length;
        for (int i = 0; i < intChromosomeCount; i++)
          this.arrChromosomes[i] = this.randomizer.nextBoolean();
       * Get fitness of this individual
       * In case of knapsack, fitness is sum of prices of all things currently in knapsack
       * @see Individual#getFitness()
      protected int getFitness()
        //if cached value exist, return it
        if (this.intFitnessCache != Integer.MIN_VALUE)
          return this.intFitnessCache;
        //otherwise, count fitness of this individual
        int intChromosomeCount = this.arrChromosomes.length;
        int intSumOfValues = 0;
        //in case of knapsack, fitness is value of all things currently in knapsack
        //(sum of values of all things in knapsack)
        for (int i = 0; i < intChromosomeCount; i++)
          intSumOfValues = this.assignment.arrPrices;
    //save counted fitness to cache
    this.intFitnessCache = intSumOfValues;
    return intSumOfValues;
    * Cross-breed two individuals
    * @param other The other individual for cross-breed
    * @return The other individual after cross-breed (but this individual is affected too)
    * @see Individual#crossbreed()
    protected Individual crossbreed(Individual other)
    int intChromosomeCount = this.arrChromosomes.length;
    //position from which on swap chromosomes of this and the other individual
    int intCrossbreedPosition = this.randomizer.nextInt(intChromosomeCount);
    boolean booTemp;
    //swap chromosomes from cross-breed position on
    for (int i = intCrossbreedPosition; i < intChromosomeCount; i++)
    booTemp = ((KnapsackIndividual) this).arrChromosomes[i];
    ((KnapsackIndividual) this).arrChromosomes[i] = ((KnapsackIndividual) other).arrChromosomes[i];
    ((KnapsackIndividual) other).arrChromosomes[i] = booTemp;
    return other;
    * Mutate individual chromosomes of this individual with certain probability
    * In case of knapsack, particular thing is just inserted/taken out of the knapsack
    * @see Individual#mutate()
    protected void mutate()
    //probability of mutation (in percents)
    int intMutationProbability = this.evolution.getMutationProbability();
    int intChromosomeCount = this.arrChromosomes.length;
    //iterate through all chromosomes, mutating them with certain (set) probability
    for (int i = 0; i < intChromosomeCount; i++)
    //mutation probability passed => mutate this chromosome
    if (this.randomizer.nextInt(100) < intMutationProbability)
    this.arrChromosomes[i] = !this.arrChromosomes[i];
    //when mutation finished, we must check if this individual still suits the assignment;
    //if not, repait it
    this.check();
    * Check if this individual still suits the assignment; if not, repair it
    * In case of knapsack it means that sum of weights of things currently in knapsack
    * will not exceed capacity of backpack; if exceeds, take out as many things as necessary
    * to not to exceed again; choose things to be taken out according to worst weight to price ratio
    * @see Individual#check()
    protected void check()
    int intSumOfWeights = 0;
    //list of things in the knapsack sorted by weight to price ratio
    //key: index of thing in knapsack
    //value: weight/price ratio
    TreeMap<Integer, Float> things = new TreeMap<Integer, Float>();
    for (int i = 0; i < this.arrChromosomes.length; i++)
    //thing in the knapsack
    if (this.arrChromosomes[i] == true)
    //add its weight to sum of weights
    intSumOfWeights += this.assignment.arrWeights[i];
    //add it to the list of things sorted by weight to price ratio
    things.put(i, (((float) this.assignment.arrWeights[i]) / ((float) this.assignment.arrPrices[i])));
    //sum of weights exceeds knapsack capacity => take out as many things as necessary
    while (intSumOfWeights > this.assignment.getKnapsackCapacity())
    //take out thing with worst weight/price ratio from all things currently in knapsack
    this.arrChromosomes[things.lastKey()] = false;
    //update sum of weights of things currently in knapsack
    intSumOfWeights -= things.get(things.lastKey());
    //also remove this thing from list of things
    things.remove(things.lastKey());
    And another class, where i need this feature (tried to use generics for that, but they can't be used in this way):
    * Evolution.java
    * Created on 21. leden 2007, 2:47
    package genetics;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
    * Class for algorithms using simulated evolution to deal with a problem
    * Tried to be designed general enough to allow to be used for every genetic algotihm.
    * If true, only class Individual must be implemented according to problem to be solved,
    * the rest of genetic algorithm stays the same.
    * @author Richard V�tek
    * @version
    public class Evolution<Problem, IndividualClass extends Individual>
       * Number of generations of evolution to finish
      protected int intGenerationCount;
       * Number of individuals in each generation
      protected int intGenerationSize;
       * Elite individual count
       * All elite individuals are just copied from one generation to another with no change
      protected int intGenerationEliteCount;
       * Number of individuals participating a tournament
       * To select an good individual for next generation, tournaments are hold.
       * This affects number of individuals which one good individual is selected
       * from in one tournament.
       * @see <a href="http://cs.felk.cvut.cz/%7Exobitko/ga/example_f.html">Genetic Algorithm Example Applet</a>
      protected int intGenerationTournamentSize;
       * Probability of mutation (in percents)
      protected int intMutationProbability;
       * Current generation of individuals in evolution
      protected Generation<IndividualClass> thisGeneration;
       * Next generation of individuals in evolution
      protected Generation<IndividualClass> nextGeneration;
       * Fitness of best individual in this generation
      private int intIndividualBestFitness;
       * Sum of fitnesses of all individuals in this generation
      private int intIndividualsSumFitness;
       * Fitness of worst individual in this generation
      private int intIndividualWorstFitness;
       * Fitness of best elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteBestFitness;
       * Sum of fitnesses of all elite individuals in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualElitesSumFitness;
       * Fitness of worst elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteWorstFitness;
       * Create a new instance of Evolution (settings passed through parameters)
       * @param   intGenerationCount            Number of generation of evolution to finish
       * @param   intGenerationSize             Number of individuals in each generation
       * @param   intGenerationEliteRatio       Elite individuals to generation size ratio (in percents)
       * @param   intGenerationTournamentRatio  Members of tournament to generation size ratio (in percents)
       * @param   intMutationProbability        Probability of mutation of each chromosome of each individual of generation (in percents)
       * @see     #intGenerationEliteCount
       * @see     #intGenerationTournamentSize
      public Evolution(
        int intGenerationCount, int intGenerationSize,
        int intGenerationEliteRatio, int intGenerationTournamentRatio,
        int intMutationProbability)
        this.intGenerationCount = intGenerationCount;
        this.intGenerationSize = intGenerationSize;
        this.intGenerationEliteCount = (int) (intGenerationSize * (intGenerationEliteRatio / 100.0));
        this.intGenerationTournamentSize = (int) (intGenerationSize * (intGenerationTournamentRatio / 100.0));
        this.intMutationProbability = intMutationProbability;
       * Create a new instance of Evolution (settings loaded from settings file)
       * @param   strSettingFile  Name of file containing settings for evolution
       * @throws  IOException     File does not exist, cannot be read, etc.
       * @throws  Exception       Another exception occured during loading of file
      public Evolution(String strSettingFile)
        BufferedReader settings;
        String settingsLine;
        int intLineCounter = 0;
        int intSetting;
        try
          settings = new BufferedReader(new FileReader(strSettingFile));
          while ((settingsLine = settings.readLine()) != null)
            intLineCounter++;
            settingsLine = settingsLine.substring(0, settingsLine.indexOf("\t"));
            intSetting = Integer.parseInt(settingsLine);
            switch (intLineCounter)
              case 1:
                this.intGenerationCount = intSetting;
                break;
              case 2:
                this.intGenerationSize = intSetting;
                break;
              case 3:
                this.intGenerationEliteCount = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 4:
                this.intGenerationTournamentSize = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 5:
                this.intMutationProbability = intSetting;
                break;
            } //switch
          } //while
          //after reading has been completed, let's close the stream
          settings.close();
        } //try
        //IO exception - file not found, cannot be read, etc.
        catch (IOException ioe)
          System.out.println("Vyskytl se I/O probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru " + strSettingFile);
        //Exception - another problem during reading of file
        catch (Exception e)
          System.out.printf("Vyskytl se n&#283;jak� divn� probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru %s. V�pis vyj�mky:\n", strSettingFile);
          e.printStackTrace();
       * Vivify first generation for evolution
       * Necessary number of individuals is created with random chromosomes.
       * Their chromosomes must then be checked if they suit the assignment
       * and if not so, repaired.
      private Generation<IndividualClass> vivifyFirstGeneration()
        //create a brand-new generation
        Generation generation = new Generation<IndividualClass>(this);
        int intTemp;
        //for all individual of this generation
        for (int i = 0; i < this.intGenerationSize; i++)
    //create an individual with no chromosomes
    generation.arrIndividuals[i] = new IndividualClass(this, Problem);
          //create a set of random chromosomes
          neration.arrIndividuals.createRandomChromosomes();
    //if these chromosomes does not suit assignment, repair them
    generation.arrIndividuals[i].check();
    //sort Individuals by fitness so elite individuals get to first positions of array
    Arrays.sort(generation.arrIndividuals);
    //now count statistics for elite individuals (it is enough to count them once,
    //elite don't get changed so their statistics don't get changed either)
    this.intIndividualEliteBestFitness = Integer.MIN_VALUE;
    this.intIndividualElitesSumFitness = 0;
    this.intIndividualEliteWorstFitness = Integer.MAX_VALUE;
    //count statistics for elite individuals
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    intTemp = generation.arrIndividuals[i].getFitness();
    //better fitness than best fitness so far
    if (intTemp > this.intIndividualEliteBestFitness)
    this.intIndividualEliteBestFitness = intTemp;
    //worse fitness than worst fitness so far
    else if (intTemp < this.intIndividualEliteWorstFitness)
    this.intIndividualEliteWorstFitness = intTemp;
    this.intIndividualElitesSumFitness += intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //count generation's statistics also from rest of individuals
    for (int i = this.intGenerationEliteCount; i < this.intGenerationSize; i++)
    updateGenerationStatistics(generation.arrIndividuals[i].getFitness());
    return generation;
    * Get next generation in evolution
    * Core method for all evolution; Through this method, new generation is obtained.
    * Every next generation should contain better individuals than the previous one
    * (till certain point) so with growing number of iterations in evolution, we
    * get better results (till certain point).
    * Everytime all elite individuals are copied to next generation, then hold needed number of
    * tournaments to choose a pair of good-looking individuals, cross-breed individuals in these
    * pairs, mutate them (and repair if necessary) and finally add to next generation.
    * @return Generation Next generation in evolution
    * @see Generation#tournament()
    * @see Generation#crossbreed()
    * @see Generation#mutate()
    private Generation getNextGeneration()
    Generation nextGeneration = new Generation(this);
    //number of pairs of individuals to select for next generation
    int intIndividualPairsToSelect = (this.intGenerationSize - this.intGenerationEliteCount) / 2;
    int intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //just copy all elite individuals from this generation to another
    //(they are on first positions of array of individuals)
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    nextGeneration.arrIndividuals[i] = this.thisGeneration.arrIndividuals[i];
    //hold as many tournaments as necessary to select remaining number of pairs
    //of good-looking individuals for next generation (apart from the elite ones)
    for (int i = 0; i < intIndividualPairsToSelect; i++)
    this.thisGeneration.tournament();
    this.thisGeneration.crossbreed();
    this.thisGeneration.mutate();
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i] = this.thisGeneration.nextGenerationIndividual01;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual01.getFitness());
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i + 1] = this.thisGeneration.nextGenerationIndividual02;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual02.getFitness());
    //next generation is complete => return it
    return nextGeneration;
    * Update statistics of current generations
    * @param intFitness Fitness that may possibly update generation's statistics
    * (best fitness, worst fitness, sum of fitnesses)
    private void updateGenerationStatistics(int intFitness)
    //better fitness than best fitness so far
    if (intFitness > this.intIndividualBestFitness)
    this.intIndividualBestFitness = intFitness;
    //worse fitness than worst fitness so far
    else if (intFitness < this.intIndividualWorstFitness)
    this.intIndividualWorstFitness = intFitness;
    //update sum of fitnesses as well (for average fitness)
    this.intIndividualsSumFitness += intFitness;
    * Execute evolution process
    * Vivify first generation and then as many next generations as set in settings of evolution
    public void evolution()
    this.thisGeneration = vivifyFirstGeneration();
    //output generation's statistics
    System.out.printf("Generace 0:\t%d\t%d\t%d", this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    for (int i = 0; i < this.intGenerationCount; i++)
    this.nextGeneration = getNextGeneration();
    this.thisGeneration = this.nextGeneration;
    //output generation's statistics
    System.out.printf("Generace %d:\t%d\t%d\t%d", i, this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    * Get best fitness of all individuals in this generation
    public int getIndividualBestFitness()
    return intIndividualBestFitness;
    * Get average fitness of all individuals in this generation
    public float getIndividualAverageFitness()
    return (this.intIndividualsSumFitness / (float) this.intGenerationSize);
    * Get worst fitness of all individuals in this generation
    public int getIndividualWorstFitness()
    return intIndividualWorstFitness;
    * Get probability of mutation
    * @return Probability of mutation of each chromosome of every individual in generation (in percents)
    public int getMutationProbability()
    return intMutationProbability;

  • How to implement the abstract classes MessageDigest and Signature?

    Hi all,
    I've recently started working on JCDK 2.2.1.
    I have a problem to share and get suggestions from you!
    My aim is to implement ECDSA on Java card
    I have seen the Javacard API and tried to program using the classes
    MessageDigest and Signature. They are abstract classes and except the
    Method getInstance in them, the rest of all methods are declared abstract.
    Does that mean we have to give definition for them or else can we use
    them as they are?
    I tried giving some definitions, but to my surprise there's no such
    initiation of any variable to the algorithm we provide in the method
    "getInstance"! Then, it's not possible to give defn,. for other
    methods like getAlgorithm, reset, etc. How can we resolve this ?
    Any ideas?
    Regards,
    Johnbuchk

    try this...
    http://developer.sonyericsson.com/site/global/techsupport/tipstrickscode/java/p_java_0501.jsp
    hope it can help u

Maybe you are looking for

  • Transaction iview Unable to Connect to Backend

    Transaction iview Unable to Connect to Backend Hi guys, I am new to SAP and i am having several issues. Right now i am stuck here, in the NetWeaver Portal: I have created a Transaction iview and a System with Alias "SAP_R3". When i preview the iview

  • Some services in maintenance state after reboot

    Hi, I installed solaris 10 and everything ran fine for a month. I recently upgraded memory on the server and when I rebooted, some of the services were put in the maintenance mode. Here is the solaris 10 release info: bash-3.00# cat /etc/release Sola

  • Creating interactive forms

    I used to be able to turn regular documents and PDFs into interactive forms by adding fields.  I don't remember what program this was but I no longer have it.  I wonder if Adobe CreatePDF has this function.

  • Usage Decision screen

    Dear All, in the organisation i work for have WM also implemented. i have a scenario where, once the user made the UD, QI stock will post to unrestricted. after that i have to go to the MB51 and get the material document and manually post that stock

  • Excise Amount with three Digit decimal value

    Dear All, I enabled three digit decimal values for sales. When I am raising a Excise Invoice through J1I3, two digit only appearing? For Ex: Excise amount in sale order is 6897.525 where as in J1I3 transaction, it's showing as 68975.25. How to correc