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;

Similar Messages

  • How to implement the abstract classes MessageDigest and Signature?

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

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

  • Dynamically invoke methods of abstract class?

    Hi,
    I am using reflection to write a class (ClassA) to dynamically invoke methods of classes. I have an abstract class (ClassB) that has some of the methods already implemented, and some of the methods that are declared abstract. Is there any way that I can:
    (a) invoke the methods that are already implemented in ClassB;
    (b) I have another class (ClassC) that extends ClassB, some of the methods are declared in both classes. Can I dynamically invoke these methods from ClassB?
    Thanks in advance,
    Matt.

    Ok, the program is quite long, as it does other things as well, so I'll just put in the relevant bits.
    What I have is a JTree that displays classes selected by the user from a JFileChooser, and their methods.
    // I declare a variable called executeMethod
    private static Method executeMethod;
    // objectClass is a class that has been chosen by the user.  I create a new instance of this class to execute the methods.
    Object createdObject = objectClass.newInstance();
    // methodName is the method selected by the user.  objectClassMethods is an array containing all the methods in the chosen class.
    executeMethod = objectClassMethods[j].getDeclaringClass().getMethod(methodName, null);
    Object executeObject = executeMethod.invoke(createdObject, new Object[]{});Ok, here are the test classes:
    public abstract class ClassB{
         private int age;
         private String name;
         public ClassB(){ age = 1; name="Me";}
         public int getAge(){ return age; }
         public String getName(){ return name; }
         public void PrintAge(){System.out.println(age);}
         public void PrintName(){System.out.println(name);}
         public abstract void PrintGreeting();
    public class ClassC extends ClassB{
         public ClassC(){super();}
         public void PrintAge(){
              System.out.println("I am " + getAge() + " years old.");
         public void PrintGreeting(){
           System.out.println("Hello");
    }Now, I can print out the PrintAge method from ClassC (i.e. have it output "Hello" to the command line, how can I, say, get it to output the result of PrintName from ClassB, this method does not appear in ClassC. As you can see at the top, I can create a new instance of a normal method (in this case, ClassC), and have it output to the command line, but I know that I can't create a new instance of an abstract class. And since PrintName is implemented in abstract class ClassB, how do I get it to output to the command line?
    Thanks,
    Matt.

  • Abstract class and class

    What is the difference between abstract class and class in java?

    arcadesstuff wrote:
    Abstract class: a class that contains at least one abstract method. As has already been mentioned, abstract classes need not contain any methods at all. Have a look at the abstract class you posted; it's still abstract, though it contains no abstract methods. Note that if one declares any method of a class abstract, the class itself must be declared abstract as well.
    When you implement the abstract class Animal, you will have to write the code of those two abstract methods from above.Your example contains no abstract methods. Abstract methods must be marked with the keyword "abstract".
    ~

  • Abstract class reference itself

    How do I reference an abstract class to itself.
    public abstract class SomeClass {
       public static SomeType SomeMethod(){
             SomeClass mine = new SomeClass();
       }It gives me an error saying it can not instantiate the class.

    Possible source of confusion: you can declare a variable of type abstract class and assign it an object of a derived class that fully implements the abstract class. For instance:
    abstract class SomeClass
         public static void SomeMethod(){}
         public abstract void greeting();
    class AnotherClass extends SomeClass
         public void greeting()
              System.out.println("hello");
    public class DemoAbstractClasses
         public static void main(String args[])
              SomeClass A = new AnotherClass(); // A's type is an abstract class
              A.greeting();  //polymorphism
    }

  • Abstract Class Misunderstanding

    I have a GUI Main class that has action listeners that need to call sub classes passing in data entered by the interacting user. The subclass being called from the GUI is an Abstract class. Since abstract classes can't be instantiated, how do I pass down the data entered by the user? If this does not make sense, please reply so and I'll post code as an example.
    Thanks in advance.

    You pass an instance of a subclass of the abstract class, one that is not itself abstract.

  • Doubt on abstract classes

    Hi,
    I have doubt in abstract classes,please clarify my doubt.....my doubt is
    I have one abstract class,in that i have three methods...
    Now I have created one subclass for that abstract class....
    I defined all those methods that are there in abstract class in the sub class......and I wrote some other methods in that sub class....
    Now my question is ----->can I make the methods that are declared in abstract class invisible to the people who are using the sub class???
    Please tell me the answer...
    Thanks in advance,
    sirisha.

    ya I got it....
    Please see the code and tell me wether it is correct or not...
    abstract class One
    int i=10;
    private void display()
    System.out.println("One:display");
    public void show()
    System.out.println("One:show");
    public abstract int intadd(int j);
    class Two extends One
    int i=100;
    public void display()
    super.display();
    System.out.println("TestThr:display");
    public void show()
    //super.show();
    System.out.println("TestThr:show");
    public int intadd(int j)
    if (j==1)
         return i;
         else
    return super.i;
    public class TestThr
    public static void main(String args[])
    Two t=new Two();
         t.display();
         t.show();
         System.out.println(t.intadd(1));
    }

  • Can interface extend abstract class?

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

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

  • Why cannot create instance to an abstract class?

    Dear Developers....
    abstract class can create be its own constructor but why they didn't create object

    We cann't create an object for abstract class
    because they have abstract methods which depends on
    its subclass for its implementation. if it is
    possible to create the object for abstract class
    means then you can call a method which has no
    implementation(abstract methods) which is a illegal
    one thats what the ruleWhat about classes with no abstract members?
    public abstract class A {}No danger of accessing anything illegal here.
    The rule is far more simple. By declaring a class as abstract, the creator defines that no instances of this class may exist. Period. If you could create instances, the class wouldn't be abstract anymore, per definition. It's like asking why a green light doesn't shine red. If it would, it wouldn't be green anymore.

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

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

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

  • Abstract class implementation Dos Prompt

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

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

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

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

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

  • Multiple instances of one anonymous class

    Hi,
    I am implementing the Command pattern for an interpreter. I've created a Command class to describe the common behavior of all commands and create anonymous classes to manage the few exceptions I have. This design was chosen because I have numerous commands very similar and only a few exception, and I didn't wanted to create one class by command (the ration exception/normal is really low).
    registerCommand(new Command("commandName1", specificParameters...));
    registerCommand(new Command("commandName2", specificParameters...));
    registerCommand(new Command("exception3", specificParameters...)
        protected void execute()
          exceptional treatment...
    registerCommand(new Command("commandName4", specificParameters...));I came to the point that I have two exceptions that extend the Command class in the same way and I was asking if it is possible to create two object instances of the same anonymous class?
    Or asked differently, can one confirm that generally, anonymous classes object instances are unique?
    Thanks

    OK, perhaps I wasn't clear enough...
    Let's go with an example:
    registerCommand(new Command("exception3", specificParameters...)
        protected void execute()
          x = 1;
    registerCommand(new Command("exception4", specificParameters...)
        protected void execute()
          x = 1;
      });This code fragment creates 2 objects instances of 2 different anonymous classes. You can see that these classes have exactly the same definition (but are different), and the 2 instances are different (at least because of new instruction and that the constructor arguments are different, select the whatever reason you like).
    This new Command(..) {...} syntax defines in the same instruction an instance and an anonymous class. I would like to define an anonymous class and create 2 instances from the same anonymous class. I feel no need to name the class as only 2 instances will ever been created. And I was wondering if it is possible...
    I hope it's clearer now :)

  • Abstract class implements Cloneable... How?

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

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

  • Question about abstract classes and instances

    I have just read about abstract classes and have learned that they cannot be instantiated.
    I am doing some exercises and have done a class named "Person" and an abstract class named "Animal".
    I want to create a method in "Person" that makes it possible to set more animals to Person objects.
    So I wrote this method in class Person and compiled it and did not get any errors, but will this work later when I run the main-method?
    public void addAnimal(Animal newAnimal)
         animal.add(newAnimal);
    }Is newAnimal not an instance?

    Roxxor wrote:
    Ok, but why is it necessary with constructors in abstract classes if we don�t use them (because what I have understand, constructors are used to create objects)?Constructors don't create objects. The new operator creates objects. An object's c'tor is invoked after the object has already been created. The c'tors job is to initialize the newly-created object to a valid state. Whenever a child object is created, the parent's c'tor is run before the child's c'tor, so that by the time we're inside the child's c'tor, setting up the child's state, we know that the parent (or rather the "parent part" of the object we're initializing) is in a valid state.
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

Maybe you are looking for

  • I just installed a second, larger hard drive. Can I copy all of the files?

    I have a G5 Tower with an 80GB Seagate hard drive. I just installed a 160GB Seagate in the second bay. It seems to be connected. I partitioned it. Can I now simply copy everything that was on the old hard drive onto the new one? Do I then tell the co

  • Generate TOC with Section Markers?

    It's been a while since I've had to setup and create a TOC for a single file long document, but I'm pretty sure that I've created TOCs this way in the past. So, why won't the text in Section Markers show up in the TOC? Is it even possible to generate

  • Satellite A300-1OM - No sound on TV using HDMI

    I have a Toshiba Satellite A300-1OM, and also a Toshiba HD TV with HDMI input ports. I recently bought a HDMI to HDMI cable and attached the notebook to the tv and turned the tv to the HDMI channel, and the notebook confirmed this by making the 'new

  • Automation prog for placing the file( Excel) From production server to unix

    Hi Experts, How to write a program to automate a file from production to unix server? Right now user is downloading the file from application server and sending the file thru mail.  Is it possible in ABAP or Do we need to write in Unix? Thanks In Adv

  • Audio linking

    Hello! i have a small problem, i've been searching for a way to link my audio on  my server computer... I have my TV connected to my server on line-in and my server connected to 5.1 speakers (using it for MPD and other stuff aswell). Now i would like