Abstract classes in jave.i0
I have read that you cannot create and instance of an abstract class. If that is correct how is it possiable that I can code this ?
File Myfile = new File('c:/abc.txt);
What am I missing can anyone help ?
Ohh, wait, got it.
java.io.File An abstract representation of file and directory pathnames.
It is not an abstract class, if you look at an abstract class AbstractList for example, it will say "abstract class AbstractList" in the API.
File however takes a concept common (but not necessary identical) to all operating Systems (like Windows, Linux and MacOS X), but "abstracts" it, so you the developer are not exposed to the differences between OSes.
Similar Messages
-
Most commenly used abstract class in java.
hi all,
can anyone please tell me, what is most commonly used abstract class in java. this question was asked in interview.I hate interviewers when they ask about specifics of some classes.The fact that you hate it doesn't automatically follow that it's a bad question from the perspective of the person conducting the interviewer. You don't know what the real question is.
Bad "real" question: Do you know the statistics of Java usage off the top of your head?
Good "real" question: Do you know that Object isn't Abstract and can you name a few Abstract classes off the cuff?
Even then Programmers are so literal minded - the real question may be "Talk about what you know a bit." -
Why how Abstract class for java.util.set
I need to use Set i din't find any impelemnted class for Set, i don't want HashSet or LinkedHashSet just a Set is enough for my purpose.
How can i take instance of AbstractSet it is abstract.....
Is the only way is to write my own class extending AbstractSet.
Or is there something which i'm missing
TIA NasBecause Vector isn't an ancsetor of AbstractList.
What you are trying to do is the same as saying that becasue my cousin and I have the same grandfather we must have the same parent which isn't true.
Collection
Set List
AbstractSet AbstractList
HashSet Vector -
Problem compiling Abstract class
Hi
I have writting an abstract class Sort.java and another class BubbleSort.java. I am having problems compiling BubbleSort.java class.
The following is the error message
BubbleSort.java:8: missing method body, or declare abstract
public int doSorting(int[] array);
^
BubbleSort.java:11: return outside method
return num;
^
The following is the code
public abstract class Sort
public abstract int doSorting(int[] array);
}// End of class
public class BubbleSort extends Sort
private int num = 2;
public int doSorting(int[] array);
num = num + 2;
return num;
} // end of classRemove the semi-colon.
public int doSorting(int[] array); // <------- there -
i know the concept of abstract class in java and this concept is used in interface, i.e all the methods declared in interface are abstract. i want to know how the abtract class is different from the normal class in java
TinaV wrote:
i know the concept of abstract class in java and this concept is used in interface, i.e all the methods declared in interface are abstract. i want to know how the abtract class is different from the normal class in java
The only difference is that an abstract class can't be instantiated.
Kaj -
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; -
Java abstract classes and methods
Can anyone please tell me any real time example of abstract classes and methods.
I want to know its real use. If anyone have ever used it for some purpose while programming please do tell me.Ashu_Web wrote:
No please.. I just want to know if you have used it while programming. Like "an abstract class can be used to put all the common method names in it without having to write actual implementation code."That would describe an Interface better than an abstract class. Abstract classes usually have at least some implementation.
I want to know its usage in programming, not just a definition. I guess you understand what I am looking for.Yes, and I gave you one: java.util.AbstractList. It can be found inside the src.zip in your JDK directory and it is a pretty good example for an abstract class that provides some implementation and defines exactly what is necessary to make a full List implementation. -
Calling a method from an abstract class in a seperate class
I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
Package Chatroom
public abstract class Chat
private String id;
public String getID()
return id;
protected void setId(String s)
id = s;
public abstract void sendMessageToUser(String msg);
Package Chatroom
public class Outputter
public String[] getIDs()
// This is where I get confused. I know you can't instantiate the object like:
Chat users=new Chat();
users.getID();
I have the two classes in the package and you need to that to be able to use a class' methods in another class.
Please help me :(I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
package Chatroom
public abstract class Chatter
private String id;
public String getID()
return id;
protected void setId(String s)
id = s;
I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
package Chatroom;
import java.util.Vector;
public class Broadcaster
private Vector<Chatter> chatters = new Vector<Chatter>();
public String[] getIDs()
// code here
The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings -
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. -
".. is an abstract class. It can't be instantiated"
Does anyone have an idea of how I can get rid of the above error message? Here is a bit of my code:
import java.io.*;
import java.util.Vector;
class Project3 {
private BiTree company = new BiTree();
public static void main(String[] args) throws IOException {
Project3 run = new Project3();
run.Command();
public void Command() throws IOException {}
public interface comparable {
//not sure if need this in this class, or at all
public int compare(Object object1,Object object2);
public void add() {
Employee newOne = new Employee();
System.out.println("Enter name");
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
String name = stdin.readLine();
System.out.println("Enter title");
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
String title = stdin.readLine();
System.out.println("Enter payrate");
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
payrate = Double.parseDouble.stdin.readLine();
newOne.setTitle(title);
newOne.setName(name);
newOne.setPayrate(payrate);
company.insert(newOne);
}It is not possible to create instances of an abstract class.
I hope this example helps,
abstract class Vehicle
public static void main(String arg[])
Vehicle a;
a = new Automobile(); // ok, since Automobile is a kind of Vehicle
// The class Automobile, a special case of Vehicle
class Automobile extends Vehicle -
Abstract Class can't be instantiated
Hi I'm getting the following error messages while compiling. Does any one have any idea how to get RID of it?
ERROR MESSAGES:
EditableHeaderTableExample2.java:48: inner class EditableHeaderTableExample2. MyComboRenderer is an abstract class. It can't be instantiated.
MyComboRenderer renderer = new MyComboRenderer(items);
^
EditableHeaderTableExample2.java:79: Method redefined with different return type: javax.swing.table.TableCellRenderer getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int) was java.awt.Component getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
public TableCellRenderer getTableCellRendererComponent(
^
2 errors
Here is the code:
EditableHeaderTableExample2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JComponent;
import javax.swing.JComboBox;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
import javax.swing.JTable;
import javax.swing.plaf.metal.*;
import javax.swing.JFrame;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.DefaultCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.DefaultTableCellRenderer;
public class EditableHeaderTableExample2 extends JFrame {
public static void main(String[] args) {
EditableHeaderTableExample2 frame = new EditableHeaderTableExample2();
frame.setSize(400,300);
frame.setLocation(100,100);
frame.setVisible(true);
public EditableHeaderTableExample2(){
JTable table = new JTable(10,10);
TableColumnModel columnModel = table.getColumnModel();
table.setTableHeader(new EditableHeader(columnModel));
String[] items = {"Dog","Cat"};
JComboBox combo = new JComboBox();
for (int i=0;i<items.length;i++) {
combo.addItem(items);
MyComboRenderer renderer = new MyComboRenderer(items);
EditableHeaderTableColumn col;
// column 1
col = (EditableHeaderTableColumn)table.getColumnModel().getColumn(1);
col.setHeaderValue(combo.getItemAt(0));
col.setHeaderRenderer(renderer);
col.setHeaderEditor(new DefaultCellEditor(combo));
// column 3
col = (EditableHeaderTableColumn)table.getColumnModel().getColumn(3);
col.setHeaderValue(combo.getItemAt(0));
//col.setHeaderRenderer(renderer);
col.setHeaderEditor(new DefaultCellEditor(combo));
JScrollPane pane = new JScrollPane(table);
getContentPane().add(pane);
class MyComboRenderer extends JComboBox implements TableCellRenderer
MyComboRenderer(String[] items) {
for (int i=0;i<items.length;i++) {
addItem(items[i]);
public TableCellRenderer getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
setSelectedItem(value);
return this;This is not a suggestion, it's a requirement. When you say
class MyComboRenderer extends JComboBox implements TableCellRendererthe "implements TableCellRenderer" part is a promise that your class will include a method whose signature is
Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column); -
Difference between abstract class and the normal class
Hi...........
can anyone tell me use of abstract class instead of normal class
The main doubt for me is...
1.why we are defining the abstract method in a abstract class and then implementing that in to the normal class.instead of that we can straight way create and implement the method in normal class right...../Class vs. interface
Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
Interface vs. abstract class
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class. -
Can i call non -abstract method in abstract class into a derived class?
Hi all,
Is it possible in java to call a non-abstract method in a abstact class from a class derived from it or this is not possible in java.
The following example will explain this Ques. in detail.
abstract class A
void amethod()
System.out.println(" I am in Base Class");
public class B extends A
void amethod()
System.out.println(" I am in Derived Class");
public static void main (String args[])
// How i code this part to call a method amathod() which will print "I am in Base Class
}Ok, if you want to call a non-static method from a
static method, then you have to provide an object. In
this case it does not matter whether the method is in
an abstract base class or whatever. You simply cannot
(in any object oriented language, including C++ and
JAVA) call a nonstatic method without providing an
object, on which you will call the method.
To my solution with reflection: It also only works,
if you have an object. And: if you use
getDeclaredMethod, then invoke should not call B's
method, but A's. if you would use getMethod, then the
Method object returned would reflect to B's method.
The process of resolving overloaded methods is
performed during the getMethod call, not during the
invoke (at least AFAIK, please tell me, if I'm wrong).You are wrong....
class A {
public void dummy() {
System.out.println("Dymmy in A");
class B extends A {
public void dummy() {
System.out.println("Dymmy in B");
public static void main(String[] args) throws Exception {
A tmp = new B();
Class clazz = A.class;
Method method = clazz.getDeclaredMethod("dummy", null);
method.invoke(tmp, null);
}Prints:
Dymmy in B
/Kaj -
Non-abstract methods in a Abstract class
Abstract Class can contain Non-abstract methods.
and Abstract Classes are not instantiable as well
So,
What is the purpose of Non-abstract methods in a Abstract class.
since we can't create objects and use it
so these non-abstract methods are only available to subclasses.
(if the subclass is not marked as abstract)
is that the advantage that has.(availability in subclass)
??For example, the AbstractCollection class (in
java.util) provides an implementation for many of the
methods defined in the Collection interface.
Subclasses only have to implement a few more methods
to fulfill the Collection contract. Subclasses may
also choose to override the AbstractCollection
functionality if - for example - they know how to
provide an optimized implementation based on
characteristics of the actual subclass.Another example is the abstract class MouseAdapter that implements MouseListener, MouseWheelListener, MouseMotionListener, and that you can use instead of these interfaces when you want to react to one or two types of events only.
Quoting the javadocs: "If you implement the MouseListener, MouseMotionListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about." -
Implementing Comparable in an abstract class
Hi all,
I am making my first sortie with abstract classes. I have had a good look around, but would still appreciate some advice with the following problem.
In my application I have several classes that have many things in common. I have concluded therefore, that if I create and then inherit from an abstract super class, I can reduce and improve my code. I created this abstract class:
public abstract class YAbstractObject implements Comparable {
public YAbstractObject(int projectId, YObject object, String objectName) {
this.projectId = projectId; // Always the same parameters
this.object = object;
this.objectName = objectName;
// This is abstract as it must always be present for sub classes but differant processing will take place
public abstract void resolveObject();
// These three methods will always be the same for all sub classes
public String getName() {
return objectName;
public YObject getObject() {
return object;
public boolean isValid() {
return isValid;
// Overridden and always the same for all sub classes
public String toString() {
return objectName;
// implemented abstract method
public int compareTo(Object thatObject) {
// Issue here! I would like something as follows:
// return this.getName().compareToIgnoreCase(thatObject.getName());
// Variable decleration
private int projectId;
private YObject object;
private String objectName;
private boolean isValid;As I have commented in the compareTo() method, I would like it to be able to use the getName() method for comparison objects and compare them. But it does not like this, as it does not know that "thatObject" is of the same class as this object - I hope that made sense.
in essence, I want to inherit this method for different classes and have it work with each.
Is there a way to do this? Generics?
Any observations, greatly appreciated,
SteveYou can use also generics (if applicable: java -version >= 1.5).
public abstract class Test implements Comparable<Test> {
String name;
public Test(String name) {
this.name = name;
public String getName() {
return name;
public int compareTo(Test obj) {
return this.getName().compareTo(obj.getName());
public class Other extends Test {
public Other(String name) {
super(name);
public class Tester extends Test {
public Tester(String name) {
super(name);
public static void main(String[] args) {
Test t = new Tester("t");
Test a = new Tester("a");
Test o = new Other("t");
System.out.println(t.compareTo(a));
System.out.println(t.compareTo(new Object())); //compile error
System.out.println(t.compareTo(o));
}Without the compile error line it will give the following result:
19
0
Maybe you are looking for
-
CAF Business Objects in Separate Database
We currently have an application written in CAF which is using Business Objects/Entity Services using local persistence. I believe the local persistence automatically uses the default datasource defined in the SAP WAS portal server and creates the ta
-
Hi All, I have encountered an interesting situation. While trying to post a document through an RFC I have come across two postings which have all the header and line items same except for the document number. Even the posting time is same for both e
-
Deploy of Essbase Cube from EPMA to Shared Services Project is not possible
We cannot deploy Essbase Cubes to shared services projects. The projects are not selectable in the box in the deploy dialog. Help is urgently needed. Our version is 11.1.1.3. Many thanks Michael
-
Hidden subforms when form is opened
I am having a problem with hidden subforms. I have subforms that are orginally hidden, and become visible when an item in a drop down list is selected. When I save the form, and re-open it, the subforms are hidden again. The only way to make them vis
-
SQL> ed Wrote file afiedt.buf 1 INSERT INTO IHS_PT_CASE@link_to_dmsr 2 SELECT 'IHS_OWNER', SUBSTR(TRIM(ADT_CASE.CASE_ACCOUNT_NO),1,12), 3 ADT_CASE.CASE_ADMIT_DT, ADT_CASE.CASE_DC_DT, SUBSTR(TRIM(ADT_CASE_LOCATION.LOCN_NSG_STATN_CD),1 4 SUBSTR(TRIM(AD