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

Similar Messages

  • Interfaces / Abstract classes / ResultSets

    I want to set the fetch size of each java.sql.ResultSet throughout my application, in one place. ResultSet is an interface and a ResultSet is returned by a call to PreparedStatement.execute(). So I figured I could implement ResultSet in an abstract class of my own and just override getFetchSize() or put a setFetchSize() in the constructor. Anyway, it seems I get a ClassCastException when casting the ResultSet returned from PreparedStatement.execute() to MyResultSet:
    java.lang.ClassCastException: oracle.jdbc.driver.OracleResultSetImpl
    I've tried having MyResultSet implement oracle.jdbc.driver.OracleResultSet too just in case. But no luck there either. If I try and implement OracleResultSetImpl I'm told it's not public and so can't be accessed from outside the package.
    Can I do this somehow? Or an alternative, simple way?

    I want to set the fetch size of each
    java.sql.ResultSet throughout my application, in one
    place. ResultSet is an interface and a ResultSet is
    returned by a call to PreparedStatement.execute(). So
    I figured I could implement ResultSet in an abstract
    class of my own and just override getFetchSize() or
    put a setFetchSize() in the constructor.Yes, you can.
    Anyway, it
    seems I get a ClassCastException when casting the
    ResultSet returned from PreparedStatement.execute()
    to MyResultSet:Well, you have to re-implement PreparedStatement as well, otherwise of course it won't even know that your class exists, let alone use it.
    Serializabe z = method();
    If I define method() to return a String, it doesn't mean that it'll suddenly return something else simply because I wrote it and it also implements Serializable.
    java.lang.ClassCastException:
    oracle.jdbc.driver.OracleResultSetImplThe object you get is simply not an instance of your class.
    Simple way around: create a wrapper class around the original ResultSet that does what your implementation did.

  • Good programming practice - Abstract class

    Hi all,
    I have been trying to help another soul in this forum, and came to the conclusion that I don't know good
    programming practice when it comes to abstract classes.
    Is this correct?
    You CAN implement methods in an abstract class, but it's not recommended.
    I have NEVER done this...when is there possibly a need to?
    Regards.
    / k

    Yes, absolutely, you can implement methods in an abstract class. Any method that all subclasses will perform in the same way can be implemented in the abstract base class. If subclasses perform similiar functions depending on their type you declare those as abstract in the base class. Here is a contrived example that I have seen on job interviews.
    Suppose your developing an application that draws on a panel. We want to provide some canned shapes such as a circle, a square and a triangle. We want to be able to draw the shape set or get its color and calculate its area.
    Let's define an abstract base class Shape
    public abstract class Shape{
        private Color myColor;
       //  since color has nothing to do with what kind of shape we're working with, create concrete implementation
       public Color getColor(){
            return myColor;
    public void setColor(Color newColor){
       myColor = newColor;
    // however, drawing the shape and calculation its area are depending on the actual shape.
    public abstract void draw();
    public abstract double getArea();
    // so then Square would be something like
    public class Square extends Shape{
       public double get Area()
          return sideLength * sideLength  // assumes somehow we know sideLength
    public void draw(){
                  // concrete implementation
    }we can do the same things for Circle class and Triangle class.
    And, if you think about it you'll notice that we could have made a Rectangle class and then Square would be a subclass of Rectangle where both dimensions are equal.
    I hope that somewhat strained example helps answer your question.
    DB

  • Can interface extend abstract class?

    Can interface extend abstract class?
    I tried to make a interface extend an abstract class but i got an error stating:
    interface expected here.
    Can anyone help me ?

    > ok, but can an interface implement an abstract class?
    No. An interface provides no implementation whatsoever. An abstract class can implement an interface, but not the other way around.
    http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
    ~

  • Abstract Class that implements Comparable

    I am trying to understand how a comparable interface works with an abstract class. Any help is greatly appreciated.
    I have a class ClassA defined as follows:
    public abstract class ClassA implements Comparable I have a method, compareTo(..), within ClassA as follows:
    public int compareTo(Object o) I have a sub-class ClassB defined as follows:
    public class ClassB extends ClassAI am receiving a compile error:
    Class must implement the inherited abstract method packagename.ClassA.compareTo(Object)
    Should or can the compareTo be abstract in ClassA and executed in ClassB? Just not sure how this works.

    ???? if you are inheriting from an abstract class your subclass must implement methods that were declared in the parent (abstract) class but not implemented
    When in doubt, refer to the Java Language Specification..

  • When to use abstract class compared to interface

    hi
    can some one plase advise me when to use abstract class compared to interface?
    Example will be appreciated...

    So an abstract class can carry implementation. This can be used to formulate a rule of thumb as to when to use it over an interface.
    If you have a so called type specialization relationship between the subtypes and the supertype then they're likely to benefit from shared implementation provided by the supertype, so use class (abstract or concrete) extension in this case. Type specialization is when the supertype represents a general concept like Fruit and the subtypes are specialized forms of that like Apple and Banana.
    Another common kind of relationship is called type expansion. In this case the subtypes are unlikely to have any use of implementation provided by the supertype, so use interface implementation. Type expansion is when the supertype represents a specific character the subtypes take on. For example Apple and Bicycle ure unrelated in the type specialization sense but still can share a common character like Comparable. The subtypes have been expanded to include the supertype character, namely the ability to be compared.

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

  • MyInteger class- compile error - method doesnt implement comparable method

    I am trying to test how the code for a hash table works- I have 4 classes
    Hashable interface
    QuadraticProbableHashTable
    HashEntry
    MyInteger
    Everything is compiling but one error comes up saying that "Class must implement the inherited abstract method Comparable.compareTo(object)."
    I have a comparable method with the same signature as that in Comparable interface; in MyInteger.java where the problem is. However I still have the same problem.
         * Wrapper class for use with generic data structures.
         * Mimics Integer.
        public final class MyInteger implements Comparable, Hashable
             * Construct the MyInteger object with initial value 0.
            public MyInteger( )
                this( 0 );
             * Construct the MyInteger object.
             * @param x the initial value.
            public MyInteger( int x )
                value = x;
             * Gets the stored int value.
             * @return the stored value.
            public int intValue( )
                return value;
             * Implements the toString method.
             * @return the String representation.
            public String toString( )
                return Integer.toString( value );
             * Implements the compareTo method.
             * @param rhs the other MyInteger object.
             * @return 0 if two objects are equal;
             *     less than zero if this object is smaller;
             *     greater than zero if this object is larger.
             * @exception ClassCastException if rhs is not
             *     a MyInteger.
            public int compareTo( Comparable rhs )
                return value < ((MyInteger)rhs).value ? -1 :
                       value == ((MyInteger)rhs).value ? 0 : 1;
             * Implements the equals method.
             * @param rhs the second MyInteger.
             * @return true if the objects are equal, false otherwise.
             * @exception ClassCastException if rhs is not
             *     a MyInteger.
            public boolean equals( Object rhs )
                return rhs != null && value == ((MyInteger)rhs).value;
             * Implements the hash method.
             * @param tableSize the hash table size.
             * @return a number between 0 and tableSize-1.
            public int hash( int tableSize )
                if( value < 0 )
                    return -value % tableSize;
                else
                    return value % tableSize;
            private int value;
        }

    >
    You might want to also allow for cases where the
    value passed in is null, or the argument to the
    method is NOT a MyInteger object :-)
    Just a small note - the javadocs for Comparable#compareTo says the following:
    Throws:
    ClassCastException - if the specified object's type prevents it from being compared to this Object.
    So it's perfectly OK to blindly try to cast to the desired type in the sense that you are not violating the Comparable contract if the cast fails.

  • Abstract class implementation Dos Prompt

    Hello everyone,
    Good day! Anyone knows how to implement or use abstract class to another class. Pls.... help me. I'm still a novice programmer. Program like Bank Account with a abstract class named 'Account' and an another class 'Savings' extends the abstract class and also the third class named 'TimeDeposit' something like it.

    Hello everyone,
    Good day! Anyone knows how to implement or
    use abstract class to another class. Pls.... help
    me. I'm still a novice programmer. Program like Bank
    Account with a abstract class named 'Account' and an
    another class 'Savings' extends the abstract class
    and also the third class named 'TimeDeposit'
    something like it.One thing to remember is that your class has to include code for all methods that are marked abstract in the abstract class you are extending; and if you don't want anyone else extending your class, you should make it final. You should also check the abstract class's constructors to see if you need to call a particular one when you are constructing your class. If you do, you'll need to call super(...) in your class's constructor, and it should be the first statement.

  • 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

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

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

  • Abstract class implements Cloneable... How?

    I have an abstract class that is inherited by many many subclasses. I wish to make this abstract class a cloneable.
    Most of the subclasses are using the protected fields inherited from the abstract one, they almost never add any extra field. So it would make a lot of sense to implement the clone() method at the abstract level. And not doing so would cost me a lot of time.
    But that causes me trouble, because you can't write something like this :
    public abstract class MyAbstractClass implements Cloneable {
        protected Source source; // the two fields the subclasses are satisfied with, most the time
        protected Vectro<Target> targets;
        public Effect clone() {
            return new Effect(source , targets);  // when a subclass has extra fields, I plan to overwrite clone()
    }Because you can't instantiate an abstract class, of course. Anyway, I'd rather instatiate a class of the appropriate concrete class.
    I feel there is a way to hack this. I feel there is a way to avoid having to write the same clone() method in every subclass.
    Anyone?
    Thanks.

    jverd wrote:
    bestam wrote:
    Most of the subclasses are using the protected fields inherited from the abstract one, Bad idea. Make the fields private and provide protected get/set methods.Is this a general recommendation or only in the context described by the OP?
    Because API classes don't do this in many cases. Just looked at a random one: AbstractButton.

  • 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

  • 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

Maybe you are looking for

  • Error message downloading .acsm books. Help Please?

    I downloaded two bought .acsm books from Google Play Store with no problems but when I went to download the third I get this Message. Error getting license.  License Servor Communication Problem.  E_GOOGLE_DEVICE_LIMIT_REACHED.  Can someone please he

  • Can I transfer apps from my earlier 3GS to my new 4?

    I have a new Iphone 4 and want to transfer my apps from my Iphone 3GS.  Can this be done?

  • "original file could not be found" help needed please

    Hello and help...please i have a new laptop, so i saved my itunes music library to an external drive to transfer it to the new machine. I uploaded to itunes with the simple 'add folder' option and all my songs appeared in itunes everything is great i

  • Warcraft won't open...  EXC_BAD_ACCESS (SIGBUS)

    Warcraft won't open KERNPROTECTIONFAILURE... no idea what to do? Process: World of Warcraft [258] Path: /Applications/World of Warcraft/World of Warcraft.app/Contents/MacOS/World of Warcraft Identifier: com.blizzard.worldofwarcraft Version: 4.0.6 (13

  • SSRS 2008 Running Totals - How are they created at the grouping by level

    I am trying to create the running total column(the right column) month-to-date, and I am new to SSRS.  Is this possible to do on the SSRS-side, or, will I need to do this in the SQL stored procedure that SSRS is calling? Number Enrolled Number Enroll