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 :)
Similar Messages
-
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? -
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 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?
MarcoSo 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 -
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. -
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. -
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. -
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. -
Reflection on abstract classes
import java.lang.reflect.Method;
public class MethodInfoDemo {
public static void printMethodInfo(final Object obj) {
Class type = obj.getClass();
final Method[] methods = type.getMethods();
for (int idx = 0; idx < methods.length; idx++) {
System.out.println(methods[idx]);
import javax.swing.AbstractAction;
public class ReflectScaf {
public static void main(String args[]) {
HtmlCreator h = new HtmlCreator();
MethodInfoDemo.printMethodInfo(AbstractAction());
}Hello again, how do you do reflection on abstract classes?
Because I can't instantiate AbstractAction I can't feed an object to the getMethods() method in the reflection class.
Any ideas?You don't need an instance of the class in order to do reflection. You just need the class' Class object.
import java.lang.reflect.*;
public abstract class AbstractReflection {
public static void main(String[] args) throws Exception {
Class klass = AbstractReflection.class; // or Class.forName("AbstractReflection")
Method[] methods = klass.getMethods();
for (Method m : methods) {
System.out.println(m);
public abstract int foo();
public abstract void bar(String str);
public void baz() {}
:; java -cp classes AbstractReflection
public static void AbstractReflection.main(java.lang.String[]) throws java.lang.Exception
public abstract int AbstractReflection.foo()
public abstract void AbstractReflection.bar(java.lang.String)
public void AbstractReflection.baz()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
public java.lang.String java.lang.Object.toString() -
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ři nač�t�n� zad�n� ze souboru " + strSettingFile);
//Exception - another problem during reading of file
catch (Exception e)
System.out.printf("Vyskytl se nějak� divn� probl�m při nač�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; -
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 helpI 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.
-
Why use an Abstract Class ?
I am new to Java and for some reason I can't get my head around why to use an abstract class. I understand that an abstract class is something like:
public abstract class Food{ // abstract class
public void eat(){
// stub
public class Apple extends Food{
public void eat(){
// Eat an apple code
}So basically the idea above is that you can eat an "apple" but you can't eat "food" because you can't instantiate an abstract class.
I understand what an abstract class is and how to write one. What I don't understand is why you would use it? It looks to me like I could have just created a normal class called "Food" and just not instantiated it. What are the benefits of using an abstract class?807479 wrote:
I am new to Java and for some reason I can't get my head around why to use an abstract class.One of the first books I ever read about Object-Oriented design contained the following quote from [url http://en.wikipedia.org/wiki/Lucius_Cary,_2nd_Viscount_Falkland]Lord Falkland:
"When it is not necessary to make a decision, it is necessary +not+ to make a decision."
It took me quite a while to understand, but it's all about flexibility: As soon as you cast something in stone, you lose the ability to change it later on if something better/more appropriate comes along. Interfaces and abstract classes are all about delaying that decision.
As jverd said, interfaces allow you to specify what is required without defining the how; and as ErasP said, abstract classes are usually incomplete: ie, they define some of the 'how', but not all of it.
What is most important about abstract classes though is that they cannot exist on their own: They must be extended by a concrete class that completes the 'how' before they can be instantiated and, as such, they declare the intent of the designer.
One of the most important uses of abstract classes is as "skeleton implementations" of interfaces, and there are a lot of examples of these in the Java Collections hierarchy. My favourite is probably AbstractList, which contains a skeleton implementation of a List. Because it exists, I can create a class that wraps an array as a List with very little code, viz:public final class ArrayAsList<T>()
extends AbstractList<T>
private final T[] values;
public ArrayAsList(T... values) {
this.values = values;
@Override
public T get(int index) {
return values[index];
@Override
public T set(int index, T element) {
T value = get(index);
values[index] = element;
return value;
@Override
public int size() {
return values.length;
};and somewhere else, I can use it: List<String> letters =
new ArrayAsList<String>("a", "b", "c");or perhaps, more practically: List<String> words = new ArrayAsList<String>(
bigTextString.split(" +") );Now that may not seem like a big deal to you, but given all that Lists can do, it's actually a very powerful bit of code. The above example is from "Effective Java" (p.95).
HIH
Winston -
Hi,
I have to buid a report in ECM with complete details of the engineering as well as production. This include workflow as well as various fucntionality depends upon the criterion and user's event.
I am implementating in OOPS and I Want to know that when I should use the Abstract class and when interface ?
Because as per me both serve the same purpose. Kindly send me the exact difference so that i can efficiently use the same.
Thanks
PrinceWhen inheriting A Interface We have to inherit all the methods of the Interface there's no other option whereas with abstract classes we can inherit the members that we are in need of.
Just the interface has to have body of the method and the method is to be used by the classes inheriting it. Whereas in the case of Abstract Class it can have declarations (Other than the abstract method) and it can be further extended in the classes inheriting the Abstract Class.
Interface contains all abstract methods,all methods compulsory implemented by particular class, interface does not contain Constructor
abstract classes are designed with implemantion gaps for sub-class to fill in.
interfaces are sintacticlly similar to classes but they lack insance variables & methods.
abstract classes can also have both abstract methods & non-abstract methods. where as in interface methods are abstract only, & variables are implicitly static&final
regards
Preetesh -
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. -
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
Maybe you are looking for
-
hi all, SELECT T0.[Quantity] + (T0.[Quantity]/10), T0.[ItemCode] FROM RDR1 T0 INNER JOIN ORDR T1 ON T0.DocEntry = T1.DocEntry WHERE T1.[DocNum] =[%0] This query select particular sales order and then item is selected one by one in this order, after
-
Oracle SQL Developer 1.5.1
Hi, I have problem after getting data from database, is look like that: http://images46.fotosik.pl/39/aed67a246d542dae.jpg The data are not clear, I have to do Refresh to get this fix. Is happen only during scrolling vertical or horizontal. Is not a
-
Upload Data Periodically using FV75 based on Customer No
Hi Guys, I'm very new to SAP. Here i'm facing one problem that i've to upload Data from File to SAP for FV75 transaction. I tried Recording but it's not possible. Then i tried BAPI like MRM_PARKED_INVOICE_ACCDATA, AC_DOCUMENT_PARKING_NO_UPDATE, and
-
Installing OSB11g 11.1.1.4.0
Hi, I am new to OSB. I have downloaded the ofm_osb_generic_11.1.1.4.0_disk1_1of1.zip and extracted this file which contains disk1 and disk2. Whether is it necessary to copy the contents of disk2 into disk1 before installing??? Or the installer automa
-
I can't run videos using my Safari browser, only on Foxfire. On Safari when I try to run a video, I get a message that says my Adobe flash player is out of date and to download new adobe flash. However, when I try to run the Adobe Flash player inst