Final field in abstract class

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

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

Similar Messages

  • Invoking method of final subclass of abstract class is slow

    hi,
    I've diagnosed a performance regression in my code which boils down to the example at the end of the post.
    Would it be possible to have the vm dynamically figure out that within the hotspot in the test method, its
    safe to ditch the dynamic dispatch and skip that overhead?
    I thought marking the method as final would allow the vm to peform some run-time optimisations - I'm pretty sure I've been able to measure that in different situations; marking the test method's parameter (a) as final, also doesn't help.
    Rather than have an abstract class, its looking like the performance requirements will dictate some copy and paste to
    help the vm along - does anyone know if I'm missing something here?
    thanks in advance,
    asjf
    The output I see (using 6.0 update 10) is:
    B foo 28
    B bar 95
    C foo 29
    C bar 86
    D foo 26
    D bar 92
    E foo 29
    E bar 82
    public class MethodCallPerfTest {
         public static void main(String[] args) {
              test(new B());
              test(new C());
              test(new D());
              test(new E());
         public static void test(A a) {
                   long start= System.currentTimeMillis();
                   for(int i=0; i<8000000; i++)
                        a.foo();
                   System.out.println(a.getClass().getSimpleName()+" foo "+(System.currentTimeMillis() - start));
                   long start= System.currentTimeMillis();
                   for(int i=0; i<8000000; i++)
                        a.bar();
                   System.out.println(a.getClass().getSimpleName()+" bar "+(System.currentTimeMillis() - start));
    abstract class A {
         int j;
         final void foo() {j++;}
         abstract void bar();
    final class B extends A {
         int k;
         void bar() {k++;}
    final class C extends A {
         int l;
         final void bar() {l++;}
    class D extends A {
         int m;
         final void bar() {m++;}
    class E extends A {
         int n;
         void bar() {n++;}
    }

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

  • Final methods in abstract classes?

    Hi, why is it possible to define a final method in an abstract class? The theory behind a final method doesn't say that a final method couldn't be overridden?
    Marco

    So it's formally correct but it doesn't have any
    sense, does it?You sound very confused. A final method in an
    abstract class has just the same semantics and
    makes just as much sense as in a non-abstract
    class.
    The semantics of a final method is simply that
    it cannot be overridden in subclassed. Both
    abstract and non-abstract classes can be
    subclasses. So why do you think there should be any
    difference?Actually i was confused now it's clear. I was too binded to the concept that the extending class SHOULD(not for a formal reason, but for a 'design' one) write the implementation of the methods defined in the abstract class. Now i see that, actually, by defining a final method in an abstract class we are defining our design as implemented and clients(i.e. subclasses) can only use it.
    Thank you,
    Marco

  • Casting & abstract class & final method

    what is casting abstract class & final method  in ABAP Objects  give   some scenario where  actually  use these.

    Hi Sri,
    I'm not sure we can be any more clear.
    An Abstract class can not be instantiated. It can only be used as the superclass for it's subclasses. In other words it <b>can only be inherited</b>.
    A Final class cannot be the superclass for a subclass. In other words <b>it cannot be inherited.</b>
    I recommend the book <a href="http://www.sappress.com/product.cfm?account=&product=H1934">ABAP Objects: ABAP Programming in SAP NetWeaver</a>
    Cheers
    Graham

  • Final in abstract class, again

    Hello,
    Consider an abstract class with a final variable:abstract class RingRing {
      private final int m;
    } upon compiling, you will find a compiler error.
    Couldn't this error be delayed and placed on the implementors of this class?
    Why was it designed this way?
    The solution to this problem is to set the variable via a constructor,
    but it's a bit of a 'hack' to pass everything in the constructor. specially
    if we would like to pass it, say, an array of some yet unknown size, or ...

    Hello,
    Consider an abstract class with a final
    variable:abstract class RingRing {
    private final int m;
    } upon compiling, you will find a compiler
    error.
    Couldn't this error be delayed and placed on the
    implementors of this class?Well, considering it's private, implementors don't
    have access to it.oops, i did not mean for it to be private, i meant protected or public.
    Does it compile if it's protected? At first blush,
    what seems logical to me is that if it's protected or
    public, then the compiler would complain about any
    implementor that doesn't initialize it in all its
    constructors or in an instance initializer. I've no
    clue whether it actually works that way though, and
    since I'm assigning homework anyway... :-)and yes, the problem still exists with protected :)

  • Abstract class & final class

    Which is more correct... Or which is the more preferred way.
    abstract class A
      final method1(){}
      final method2(){}
      final method30(){}
    }or
    final class A
      private A(){}
      method1(){}
      method2(){}
      method3(){}
    }My understanding is that both classes cannot be instantiated. The first one requires writing 'final' for EACH method. The second one involves writing a private constructor.

    It depends on what you are trying to do. If you are trying to make a class that can be sub-classed but has some methods that cannot be overriden, then "abstract class A" with final methods is the way to go. If you want a class that cannot be sub-classed or instantiated then "final class A" with private constructor is the way to go.
    classes cannot be instantiatedOnly true for "final class A" because you made the only constructor private. Not true for the abstract one.// you forgot return values for the methods
    abstract class A
      final static /*void*/ method1(){}  // package private
      final static /*void*/ method2(){}  // package private
      final static /*void*/ method30(){} // package private
    // this would work
    A a = new A(){};
    // if I am in the same package as A, then this would work
    a.method1();
    // or this
    public class B extends A
      public B(String whatever)
        // Although, I cannot override the super methods
        // becuase they are all declared as final
        // I can only invoke them if I am in the same package.  You
        // declared them as package private instead of class "private"
    }Using final as a class modifier disables the ability to sub-class it but does not disable the ability to create an object of that class. You must make a private constructer. If the only constructor is "private" then you can't subclass or instantiate, so making the class final is uneeded.

  • Abstract Class Compiling Problem

    This is my first time using the code tags, I apologize if I didn't do it right.
    I can't seem to get the subclass to compile properly. I have defined an abstract class TemplateLoginCommand that encapsulates all of the login functionality. I have defined two abstract classes success and failure that should hold the code to forward the app to the right page on success, or handle any errors on login. I keep getting the following error message when I try to compile KlLoginCommand:
    I am removing the package info so my boss doesn't flip
    ../command/KlLoginCommand.java [17:1] ../command.KlLoginCommand should be declared abstract; it does not define failure() in ../.command.TemplateLoginCommand
    public class KlLoginCommand extends TemplateLoginCommand
    ^
    1 error
    Can anyone see what I am doing wrong here. I don't have a lot of experience with abstract classess/methods. Thanks
    public abstract class TemplateLoginCommand extends PageVerificationCommand implements Constants
        // Required Form Fields
        public static final String[] REQUIRED_FIELDS = {USERNAME, PASSWORD};
        // Abstract Methods Must Be Subclasses
        abstract void success(UserEntity entity);
        abstract void failure();
        /** Creates new TemplateLoginCommand */
        public TemplateLoginCommand()
            super();
        public TemplateLoginCommand(String childDirectory)
            super(childDirectory);
        public void destroy(Map map) throws Exception
            super.destroy(map);
            // Validate
            if (verifyFields(REQUIRED_FIELDS, map))
                // Attempt login
                try
                    String username = (String) map.get(USERNAME);
                    String password = (String) map.get(PASSWORD);
                    UserEntity user = UserEntity.login(username, password);
                    // Forward to rolemenu
                    success(user);
                    return;
                catch( SQLException sqle )
                    failure();
                    return;
            else
                failure();
                return;
    public final class KlLoginCommand extends TemplateLoginCommand
        /** Creates a new instance of KlLoginCommand */
        public KlLoginCommand()
        protected void failure()
        protected void success(UserEntity entity)
    }

    Hi,
    Try making the methods
    // Abstract Methods Must Be Subclasses
    abstract void success(UserEntity entity);
    abstract void failure();
    protected.
    Roger

  • Abstract classes and methods with dollar.decimal not displaying correctly

    Hi, I'm working on a homework assignment and need a little help. I have two classes, 1 abstract class, 1 extends class and 1 program file. When I run the program file, it executes properly, but the stored values are not displaying correctly. I'm trying to get them to display in the dollar format, but it's leaving off the last 0. Can someone please offer some assistance. Here's what I did.
    File 1
    public abstract class Customer//Using the abstract class for the customer info
    private String name;//customer name
    private String acctNo;//customer account number
    private int branchNumber;//The bank branch number
    //The constructor accepts as arguments the name, acctNo, and branchNumber
    public Customer(String n, String acct, int b)
        name = n;
        acctNo = acct;
        branchNumber = b;
    //toString method
    public String toString()
    String str;
        str = "Name: " + name + "\nAccount Number: " + acctNo + "\nBranch Number: " + branchNumber;
        return str;
    //Using the abstract method for the getCurrentBalance class
    public abstract double getCurrentBalance();
    }file 2
    public class AccountTrans extends Customer //
        private final double
        MONTHLY_DEPOSITS = 100,
        COMPANY_MATCH = 10,
        MONTHLY_INTEREST = 1;
        private double monthlyDeposit,
        coMatch,
        monthlyInt;
        //The constructor accepts as arguments the name, acctNo, and branchNumber
        public AccountTrans(String n, String acct, int b)
            super(n, acct, b);
        //The setMonthlyDeposit accepts the value for the monthly deposit amount
        public void setMonthlyDeposit(double deposit)
            monthlyDeposit = deposit;
        //The setCompanyMatch accepts the value for the monthly company match amount
        public void setCompanyMatch(double match)
            coMatch = match;
        //The setMonthlyInterest accepts the value for the monthly interest amount
        public void setMonthlyInterest(double interest)
            monthlyInt = interest;
        //toString method
        public String toString()
            String str;
            str = super.toString() +
            "\nAccount Type: Hybrid Retirement" +
            "\nDeposits: $" + monthlyDeposit +
            "\nCompany Match: $" + coMatch +
            "\nInterest: $" + monthlyInt;
            return str;
        //Using the getter method for the customer.java fields
        public double getCurrentBalance()
            double currentBalance;
            currentBalance = (monthlyDeposit + coMatch + monthlyInt) * (2);
            return currentBalance;
    }File 3
        public static void main(String[] args)
    //Creates the AccountTrans object       
            AccountTrans acctTrans = new AccountTrans("Jane Smith", "A123ZW", 435);
            //Created to store the values for the MonthlyDeposit,
            //CompanyMatch, MonthlyInterest
            acctTrans.setMonthlyDeposit(100);
            acctTrans.setCompanyMatch(10);
            acctTrans.setMonthlyInterest(5);
            DecimalFormat dollar = new DecimalFormat("#,##0.00");
            //This will display the customer's data
            System.out.println(acctTrans);
            //This will display the current balance times 2 since the current
            //month is February.
            System.out.println("Your current balance is $"
                    + dollar.format(acctTrans.getCurrentBalance()));
        }

    Get a hair cut!
    h1. The Ubiquitous Newbie Tips
    * DON'T SHOUT!!!
    * Homework dumps will be flamed mercilessly. [Feelin' lucky, punk? Well, do ya'?|http://www.youtube.com/watch?v=1-0BVT4cqGY]
    * Have a quick scan through the [Forum FAQ's|http://wikis.sun.com/display/SunForums/Forums.sun.com+FAQ].
    h5. Ask a good question
    * Don't forget to actually ask a question. No, The subject line doesn't count.
    * Don't even talk to me until you've:
        (a) [googled it|http://www.google.com.au/] and
        (b) had a squizzy at the [Java Cheat Sheet|http://mindprod.com/jgloss/jcheat.html] and
        (c) looked it up in [Sun's Java Tutorials|http://java.sun.com/docs/books/tutorial/] and
        (d) read the relevant section of the [API Docs|http://java.sun.com/javase/6/docs/api/index-files/index-1.html] and maybe even
        (e) referred to the JLS for "advanced" questions.
    * [Good questions|http://www.catb.org/~esr/faqs/smart-questions.html#intro] get better Answers. It's a fact. Trust me on this one.
        - Lots of regulars on these forums simply don't read badly written questions. It's just too frustrating.
          - FFS spare us the SMS and L33t speak! Pull your pants up, and get a hair cut!
        - Often you discover your own mistake whilst forming a "Good question".
        - Often you discover that you where trying to answer "[the wrong question|http://blog.aisleten.com/2008/11/20/youre-asking-the-wrong-question/]".
        - Many of the regulars on these forums will bend over backwards to help with a "Good question",
          especially to a nuggetty problem, because they're interested in the answer.
    * Improve your chances of getting laid tonight by writing an SSCCE
        - For you normal people, That's a: Short Self-Contained Compilable (Correct) Example.
        - Short is sweet: No-one wants to wade through 5000 lines to find your syntax errors!
        - Often you discover your own mistake whilst writing an SSCCE.
        - Often you solve your own problem whilst preparing the SSCCE.
        - Solving your own problem yields a sense of accomplishment, which makes you smarter ;-)
    h5. Formatting Matters
    * Post your code between a pair of &#123;code} tags
        - That is: &#123;code} ... your code goes here ... &#123;code}
        - This makes your code easier to read by preserving whitespace and highlighting java syntax.
        - Copy&paste your source code directly from your editor. The forum editor basically sucks.
        - The forums tabwidth is 8, as per [the java coding conventions|http://java.sun.com/docs/codeconv/].
          - Indents will go jagged if your tabwidth!=8 and you've mixed tabs and spaces.
          - Indentation is essential to following program code.
          - Long lines (say > 132 chars) should be wrapped.
    * Post your error messages between a pair of &#123;code} tags:
        - That is: &#123;code} ... errors here ... &#123;code}
        - OR: &#91;pre]&#123;noformat} ... errors here ... &#123;noformat}&#91;/pre]
        - To make it easier for us to find, Mark the erroneous line(s) in your source-code. For example:
            System.out.println("Your momma!); // <<<< ERROR 1
        - Note that error messages are rendered basically useless if the code has been
          modified AT ALL since the error message was produced.
        - Here's [How to read a stacktrace|http://www.0xcafefeed.com/2004/06/of-thread-dumps-and-stack-traces/].
    * The forum editor has a "Preview" pane. Use it.
        - If you're new around here you'll probably find the "Rich Text" view is easier to use.
        - WARNING: Swapping from "Plain Text" view to "Rich Text" scrambles the markup!
        - To see how a posted "special effect" is done, click reply then click the quote button.
    If you (the newbie) have covered these bases *you deserve, and can therefore expect, GOOD answers!*
    h1. The pledge!
    We the New To Java regulars do hereby pledge to refrain from flaming anybody, no matter how gumbyish the question, if the OP has demonstrably tried to cover these bases. The rest are fair game.

  • SerialVersionUID in abstract classes

    Hi,
    i have a Question about the serialVersionUID for abstract classes.
    first i will describe a simple example to show my problem.
    abstract class A implements Serializable {
        private int value;
        public A(int value) {
            this.value = value;
        protected abstract void doSomething();
    class B extends A {
        private static final serialVersionUID = 8373629029L;
        public B(int value) {
               super(value);
        protected void doSomething() {
         //do something
    } B is a ValueObjects on a Server and transmitted to a Client Application.
    When i change the abstract super class A i get an exception on the client because the serialVersionUID does not mathc to the Client anymore
    So i changed the " implements Serializable" Statement down to B. And tried the same. Then i get an InvalidClassException because with following hint "no valid constructor". So i also have to make A Serializable and also need a defined serialVersionUID for A.
    I think there is something i don't unterstand in the serialization Mechanism in Java.
    Why does it makes sense to adda serialVersionUID to an abstract class? And how do i generate the UID with the "serialver" tool deliversd with the JDK form a class which i cannot instanciate?
    Edited by: kbj on Jan 23, 2009 7:14 AM

    kbj wrote:
    So i would like to know what is the best practise in such a case?Classes designed for inheritance should rarely implement Serializable, and interfaces should rarely extend it. If a class or interface exists primarily to participate in a framework that requires all participants to implement Serializable then it makes sense to violate this rule.
    So in your case you may want to provide a protected parameterless constructor and a protected initialization method if a client provided invariant is required ("value" in your case). Then all public or protected instance methods need to call a private method that checks that the class has been initialized (i.e. the subclass has been written so that it calls the protected initialization method and passes in the "value" invariant). If not then you should throw an IllegalStateException. The field you use to flag that the object has been initialized should be of type java.util.concurrent.atomic.AtomicReference.
    The above is taken pretty much verbatim from chapter 11 of effective java second edition. The book also provides an example of the above you could use as a template.

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

  • Problem with final variables and inner classes (JDK1.1.8)

    When using JDK1.1.8, I came up with following:
    public class Outer
        protected final int i;
        protected Inner inner = null;
        public Outer(int value)
            i = value;
            inner = new Inner();
            inner.foo();
        protected class Inner
            public void foo()
                System.out.println(i);
    }causing this:
    Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
    public Outer(int value)
    ^
    1 error
    With JDK 1.3 this works just fine, as it does with 1.1.8 if
    1) I don't use inner class, or
    2) I assign the value in initializer, or
    3) I leave the keyword final away.
    and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
    Reasons why I am trying to do this:
    1) I can't use a newer JDK
    2) I want to be able to assign the variables value in constructor
    3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
    4) I must be able to use inner classes
    So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?

    You cannot use a final field if you do not
    initialize it at the time of declaration. So yes,
    your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
    public class Outer {
            protected final String str;
            public Outer(String paramStr) {
                    str = paramStr;
                    Inner in = new Inner();
                    in.foo();
            public void foo() {
                    System.out.println("Outer.foo(): " + str);
            public static void main( String args[] ) {
                    String param = new String("This is test.");
                    Outer outer = new Outer(param);
                    outer.foo();
            protected class Inner {
                    public void foo() {
                            System.out.println("Inner.foo(): " + str);
    } producing the following:
    [1:39] % javac Outer.java
    [1:39] % java Outer
    Inner.foo(): This is test.
    Outer.foo(): This is test.
    Is this then an "undocumented feature", working even though it shouldn't work?
    However, I assume you could
    get by with eliminating the final field and simply
    passing the value directly to the Inner class's
    constructor. if not, you'll have to rethink larger
    aspects of your design.I guess this is the way it must be done.
    Jussi

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

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

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

  • A Singleton variable in an Abstract Class

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

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

  • Set fields of derived class in base class constructor via reflection?

    Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
    Many thanks for your feedback!
    Norman
    public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
    abstract static class A {
        A() {
            try {
                getClass().getDeclaredField("x").setInt(this, 42);
            } catch (Exception e) {
                throw new RuntimeException(e);
    static class B extends A {
        int x;
        B() {
        B(int x) {
            this.x = x;
    public void testThatItWorks() {
        assertEquals(42, new B().x);
        assertEquals(99, new B(99).x);
    }

    why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
    Framework:
    public abstract class Operator {
        public abstract void initialize();
    }Plug-In:
    public class SomeOperator extends Operator {
        @Parameter(defaultValue="42", interval="[0,100)")
        double threshold;
        @Parameter(defaultValue="C", valueSet="A,B,C")
        String mode;
        public void setThreshold(double threshold) {this.threshold = threshold;}
        public void setMode(String mode) {this.mode = mode;}
        // called by the framework after default values have been set
        public void initialize() {
    }On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance.

  • Beginner CORBA idl struct said to be abstract class

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

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

Maybe you are looking for

  • Error while trying to add a new field in search criteria by VO extension

    Hi, I am trying to add a new field by using the VO extension to a seeded OAF page used to search Repository contracts. I get the following error on opening the page after I have compiled my code on server and bounced apache. Message not found. Applic

  • Where did the album art display go?

    In iTunes 10.6 for Windows, the album art display in the Library column is gone. I can't, for the life of me, figure out how to put it back. For clarity's sake, I'm talking about the thumbnail at the bottom left corner, right under Playlists – the on

  • Hooking up M-Audio Studiopro 3 Speakers to an iMac

    Hello Folks, I'd like to hook up my M-Audio Studiopro 3 speakers to my iMac. I see the speaker input on the back of the iMac but it's only a single input, my speakers have left and right cables. Do I need to get some sort of adaptor or is there anoth

  • Project Server and Visual Studio Online

    With the release of Visual Studio Online, will we be able link Project Server 2013 to it, as we can with our on-prem TFS server? Thanks in advance, Tim

  • Problem of "assembly" HRESULT

    I can not download iTunes as it should he warned me of a problem of "assembly" HRESULT