Using an abstract method to assign an annotion property
Hi Guys
I have an annotation for specifiying that a method requires a transation. It's very simple, and looks like this:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TransationRequired
PersistenceUnitDescriptor persistenceUnitDescriptor();
}PersistenceUnitDescriptor is a simple enum, and I use Aspect J to weave code around methods annotated with this annotation.
When I annotate a method like this
@TransationRequired(persistenceUnitDescriptor = PersistenceUnitDescriptor.XXX)
public Boolean func(String xx)
//TODO: Something
}It works fine, but when I annotate like this :
@TransationRequired(persistenceUnitDescriptor = getPersistenceUnit())
public Boolean func(String xx)
//TODO: Something
}the apect code is never run.
getPersistenceUnit() is an abstract method and it is the only thing which is different between the two cases.
I'm not sure if this is beacuse of the annotation or because the weaving, but I thought I would ask in the annotation categroy just in case.
Anyone got an idea as to what may be causing this?
Thanks in advance,
Vackar
VackarAfzal wrote:
OK, Thanks for the tip. Pity that it has to be constant, in my opinion annotations would be a lot more powerful if you could dynamically change attributes. That really would make them more than just an alternative to annoying config files. But perhaps there are some technical details that I'm not aware of which makes this idea seem silly.Annotations were designed as a compile-time construct so the values within need to be compile time constants. At runtime, dynamic proxies are used to construct objects whose methods will return the values in question. You are free to construct your own objects implementing the interface of an annotation type at runtime that return values determined more dynamically.
Similar Messages
-
Why am i able to use abstract methods id they aren't yet implemented?
For example, why i can use this [http://docs.oracle.com/javase/7/docs/api/java/nio/CharBuffer.html#slice] if this is abstract?
Edited by: 947971 on 13-set-2012 10.38947971 wrote:
Yes, but if CharBuffer has a method declared:
public abstract CharBuffer slice()So i can't use the method slice() because it's not implemented.
And why , indeed, i'm able to use it?Because it is implemented by the actual class being used. You can't instantiate abstract classes, so there is a subclass of CharBuffer which does implement the method.
If you take the interface Comparable, you see that it has an (implicitly)abstract method compareTo. A class that implements Comparable is Integer, so you can easily write:
Comparable<Integer> i = new Integer(100);
i.compareTo(new Integer(55)); -
Hi,
I want to use abstract methods in ABAP. I created an abstract class as base and another 'child' class that extends that class. Now, I want to have different implementations in different child classes. The problem is that the IDE redirects me to the base class when trying to to this. There is no possibility to set the method as abstract.
Do you know if that concept is implemented at all? Maybe I just forgot to configure something?!
What do you propose?
Thank you and best regards,
DanielHi,
If you are creating Local class using SE38, then just by writing "abstact" to the method it behaves like an abstract method.
If you are creating global class SE24, then genrally all interface methods are "abstract" methods so that we can ihberit and can redefine the methods for example: "IF_FLUSH_NOTIFY~BEFORE_FLUSH_NOTIFY" symbol ~ shows that it is an abstract method in the interface before to that.
So, even if it refer to its base class you can just implement them in the child classes by inheriting it.
Hope this helps you if yes try to assign some app. points.
Regards,
Suman -
Abstract method which when implemented will have different parameters
Hello to all,
I have an assignment but not looking for someone to do it for me. I am only searching for a suggestion on how to do the following.
Imagine having an application that needs to provide an estimate of the rent for different buildings.
Basically I start with by having a class name Building. This class has an abstract method called estimateRent.
I then create two classes that extend the class Building which are named Apartment and House. Both need to have the method estimateRent.
However the problem is that the rent for the Apartment is calculated on the nights passed in the flat and the people in it, while the rent for the House is just calculated on a month bases.
This means the estimateRent method requires to have different parameters depending if it is implemented inside the Apartment class or the House class.
Now I only know of two options.
The first option is to not declare the estimateRent method as an abstract method inside the Building class and just implemented inside the Apartment and House with different parameters. I do not like this option since in the future if a new Building comes in then I would like to impose the fact that that object needs to have a calculate method.
The second option is to make the estimateRent method as abstract inside the Building class however takes a parameter of either a String array or else a Map. Then the estimateRent within the Apartment class would search for the elements tagged as nights and people, and the House class would only search for the elements tagged as months!
However do not know if there are any other, better ways on how to do this. I am using Java 1.4 however if you only have answers for Java 5.0 then please post them again since I always like to learn something new :)
Thank You for any comments.
txThe implementation changes, yes.Yes that I could understand in the Strategy Pattern (in the document I read it was being compared with the Template Pattern).
Then you need to refactor your design.I tought about that, however if you read my first post you will notice that I have different criteria on which the costs need to be estimated. While the costs for a flat are estimated on the people staying in and nights slept there, the costs for the house are based only on the months stayed there regardless of the people living in. Now for me I feel that it is bad programming practice to create one method that can have all the parameters required for any scenario. I mean the following is NOT something I am going to do:
estimateCosts(int nights, int people, int months ... etc);
That's not a very elegant way of going about it.
What is the "Context" going to have?Yep I agree, but so far my limited brain has only come up with that! I am open to any other sugestion! always if i understand it first!
Basically the Context would better be named as Criteria and it would be an interface as follows:
interface Criteria{}
Then I would create two classes that implement the Criteria object as follows:
class AppartmentCriteria implements Criteria{
public Result estimateCosts(int nights, int people);
class HouseCriteria implements Criteria{
public Result estimateCosts(int months);
Now when I recieve the inputs, depending on the scenario the Criteria is typecasted and the correct parameters passed and we recieve the Result.
I feel the above sucks since I am not seeing it as an object oriented way of doing this out! Is there any other sugestions! The refactoring thing I am intrested in! however really I can not see how such a call to that method could be refectored!
Thank You,
tx.
PS: Sun has blocked my other account as well, and this time they did not even send me an email to confirm that I was registered successfuully :( Is there someone I can contact on this? I guess next time I will reply with tx53m :) -
Parent constructor calls abstract method
Hi everybody!
I'm wondering if there is something wrong with java or if the idea is just too ill?
Anyway, I think it would be great if this hierachy would work...
Two classes A and B.
Class A defines an astract method.
In A's constructor this abstract method is called.
Class B extends A and provides an implementation for the abstract method in A.
Class B also defines a member variable that is set in B's implementation of the abstract method.
In class' B constructor the parent constructor A() is called.
example:
public abstract class A {
public A() {
createComponents();
public abstract void createComponents();
public class B extends A {
private String string = null;
public B() {
super();
System.out.println("B::B() " + string);
public void createComponents() {
System.out.println("B::createComponents() begin");
string = new String("test");
System.out.println("B::createComponents() " + string);
public void describe() {
System.out.println("B::describe() " + string);
public static void main(String[] args) {
B b = new B();
b.describe();
}running the code above produces the following output:
B::createComponents() begin
B::createComponents() test
B::B() null
B::describe() null
why is the string member variable null in B's constructor??
thanks in advance
Peter Bachl
Polytechnic University of Upper Austria, Hagenberg
[email protected]The answer is that the call of the super-constructor
is allways done before the initialization
of the member variable. That's all and that's the
normal behavior.
order :
- initialization of static variables
- call to the super-constructor
- initialization of the instance variables
- execution of the constructor
Since this is the advanced forum it is relevant to point out that that is not exactly true.
There is a step in java that 'initializes' member variables before any constructors are called, super or other wise.
From the JLS 12.5...
Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values (4.5.5)
Using the following code as an example
class MyClass
int i1;
int i2 = 1;
.When creating an instance of the above there will be three 'initializations'
// Part of object creation...
i1 = 0; // The default value
i2 = 0; // The default value
// Part of construction...after super ctors called.
i2 = 1; // The variable initializer (see step 4 of JLS 12.5)
Unfortunately the descriptions are rather similar and so confusion can result as to when the assignment actually occurs. -
Using the ContactInsertOrUpdate method from the ContactWS but error msg rcv
[This thread was migrated from the On Demand Developer Forum in the old Siebel Community]
Corsa
Contributor
I am getting the following error I do not know why or how to work around
it.
Method 'SetFieldValue' of business component 'Contact' (integration
component 'Contact') for record with search specification '[External <br/>
System Id] = "123456"' returned the following error:"Access <br/>
denied.(SBL-DAT-00542)"(SBL-EAI-04375)
Does any out there have any ideas?
Previously when I tried to do the same action I got the following message:
Multiple matches found for instance of integration component 'Contact'
using search specification '[External System Id] = "123456"' in the
business component 'Contact', based on user key 'Contact User
Key:3'.(SBL-EAI-04390)
Both messages are baffling me. Please, please help
Product: CRM OnDemand
06-16-2006 04:35 AM
Re: Using the ContactInsertOrUpdate method from the ContactWS but error
msg rcvd
BigSlick
Valued Contributor
Hi Corsa,
Can you access the record in the online application. Perhaps someone has
changed the access rights for this Contact on the Contact Team ?
-BigSlick
06-20-2006 12:33 PM
Re: Using the ContactInsertOrUpdate method from the ContactWS but error
msg rcvd
Corsa
Contributor
I realise now that the field AccountID is readonly and cannot be assigned.
I was attempting to assign contactsList[count].AccountId to a value . I
believe, this is the reason I was getting the access denied error.
06-23-2006 11:10 AM
==============================================================================
Click on the board or message subject at the top to return.Ok, so I hit a bump in the road. Just when I think I understand something It doesn't work correctly.
I implemented it I thought correctly. I looked up something on the sun website (core java) I used advice from here, and my professor finaly responded to me with almost identical instructions. So I did it
my RationalNumber.java no looks like this.
public class RationalNumber implements Comparable
//.....Break to new section
public float compute ()
float value = getNumerator() / getDenominator();
return value;
public int compareTo(RationalNumber op2)
if (Math.abs(compute() - op2.compute()) < .0001)
return 0; //Equal
if (compute() > op2.compute())
return + 1; //Rational Number bigger
if (compute() < op2.compute())
return - 1; //Rational Number Smaller
}I thought that would work fine, but it gives me an error when I compile it:
RationalNumber.java:8: RationalNumber is not abstract and does not override abstract method compareTo(java.lang.Object) in java.lang.Comparable
public class RationalNumber implements Comparable
^So now what, making it abstract only creates more errors....
Also, thanks ChuckBing, I'm glad you like the screen name, I've been using it for years. -
Should @Override apply to implementation of interface/abstract methods?
To me this is a minor but irritating incompatibility between Java 5 and 6. In 5 the @Override annotation only applied when an actual concrete method was overridden. In 6 it also applies when an interface or abstract method is implemented.
To my mind only the first case is actually overriding. Further the purpose of the @Override, AFAIKS, is to catch errors where you accidentally override a method, or write a method which you expect to override another, but get the signature wrong.
This kind of error isn't going to happen on implementing a method because you will get a real syntax error.
If we were going to use annotations to guarantee implementation it should be @Implementssabre150 wrote:
masijade. wrote:
Having spend some time recently changing from extending abstract classes to implementing interfaces I would hate to have two different annotations!It would be annoying, yes, in that case, but it would still be more "technically" correct to have a different tag. And, if we are going to insist that "newbies" here at least attempt to adhere to standards/procedures/whatever, we should be willing to do the same. ;-)It would be more "technically" correct to have an 'override' key word in the same way as in C# . The annotation approach is used to make up for a deficiency in the language specification. If one applies the KISS principle or the 'principle of least surprise' then just having one annotation makes sense.Okay then, we agree to disagree. But getting even farther away in the "use" of the term as opposed to the "definition" of the term isn't helping to make up for the deficiency in the language.
Of course, in the practical sense it is better to have one as it is, then, least likely to "break" in a backwards compatability sense (even when it only applies to compilation and not execution). -
Defining enum with abstract method which returns a generic type
Is it possible to define an abstract method which returns an geneic type like below? Thanks
public enum Type{
A{
public List<Integer> getData(){}
B{
public Set<String> getData{}
abstract<T> T getData();
}vulee wrote:
Why not?
List<Integer> lst = Type.A.getData();Wonder, which compiler you use. Can't be Java6:
# javac Enums.java
Enums.java:23: incompatible types
found : java.util.Collection<capture#376 of ?>
required: java.util.List<java.lang.Integer>
List<Integer> data = Type.A.getData();
^
1 errorEdit: Unless you do it the generic way as you proposed, which actually is a phoney. Because of the T being a generic method parameter, the compiler will infer it from the type of the variable it gets assigned to. Hence, both of the following will compile:
List<Integer> lst = Type.A.getData();
Set<String> lst2 = Type.A.getData(); // Runtime exceptionActually, javac is telling you that giving warnings on the enum constants redefined method return types.
Edited by: stefan.schulz on Sep 10, 2008 11:38 PM -
Is not abstract and does not override abstract method actionPerformed
I dont how to corr. Please help!! and thank you very much!!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test extends JFrame implements ActionListener, ItemListener
private CenterPanel centerPanel;
private QuestionPanel questionPanel;
private ButtonPanel buttonPanel;
private ResponsePanel responsePanel;
private JButton b1,b2,b3,b4,b5; //Create five references to Jbutton instances
private JTextField t1,t2,t3,t4,t5; //Create five references to JTextField instances
private JLabel label1; //Create one references to JLabel instances
private JRadioButton q1,q2,q3; //Create three references to JRadioButton instances
private ButtonGroup radioGroup; //Create one references to Button Group instances
private int que1[] = new int[5]; //Create int[4] Array
private int que2[] = new int[5];
private int que3[] = new int[5];
private String temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10,
temp11, temp12, temp13, temp14, temp15;
public test (String header)
super(header);
Container container = getContentPane();
label1 = new JLabel ("PLease click on your response to ");
q1 = new JRadioButton("I understand most of the content of this subject",true);
add(q1);
q2 = new JRadioButton("I see the relevance of the subject to my degree",false);
add(q2);
q3 = new JRadioButton("The workload in this subject is appropriate",false);
add(q3);
radioGroup = new ButtonGroup(); //JRadioButton belong to ButtonGroup
radioGroup.add(q1);
radioGroup.add(q2);
radioGroup.add(q3);
JPanel buttonPanel = new JPanel();
JPanel responsePanel = new JPanel();
JPanel questionPanel = new JPanel();
JPanel centerPanel = new JPanel();
b1 = new JButton ("Strongly DISAGREE"); //Instantiate JButton with text
b1.addActionListener (this); //Register JButtons to receive events
b2 = new JButton ("DISAGREE");
b2.addActionListener (this);
b3 = new JButton ("Neither AGREE or DISAGREE");
b3.addActionListener (this);
b4 = new JButton ("AGREE");
b4.addActionListener (this);
b5 = new JButton ("Strongly AGREE");
b5.addActionListener (this);
buttonPanel.setLayout(new GridLayout(5,1));
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
buttonPanel.add(b4);
buttonPanel.add(b5);
t1 = new JTextField ("0",3); //JTextField contains empty string
t2 = new JTextField ("0",3);
t3 = new JTextField ("0",3);
t4 = new JTextField ("0",3);
t5 = new JTextField ("0",3);
t1.setEditable( false );
t2.setEditable( false );
t3.setEditable( false );
t4.setEditable( false );
t5.setEditable( false );
responsePanel.setLayout(new GridLayout(5,1));
responsePanel.add(t1);
responsePanel.add(t2);
responsePanel.add(t3);
responsePanel.add(t4);
responsePanel.add(t5);
questionPanel.setLayout(new GridLayout(4,1));
questionPanel.add(label1);
questionPanel.add(q1);
questionPanel.add(q2);
questionPanel.add(q3);
centerPanel.add(buttonPanel,BorderLayout.CENTER);
centerPanel.add(responsePanel,BorderLayout.EAST);
container.add(centerPanel,BorderLayout.WEST);
container.add(questionPanel,BorderLayout.NORTH);
q1.addActionListener(
new ActionListener(){
public void actionPerformed( ActionEvent e )
{ //actionPerformed of all registered listeners
if (e.getSource() == b1) {
que1[0] = Integer.parseInt(t1.getText()) + 1;
String temp1 = String.valueOf(que1[0]);
t1.setText(temp1);
else if (e.getSource() == b2) {
que1[1] = Integer.parseInt(t2.getText()) + 1;
String temp2 = String.valueOf(que1[1]);
t2.setText(temp2);
else if (e.getSource() == b3) {
que1[2] = Integer.parseInt(t3.getText()) + 1;
String temp3 = String.valueOf(que1[2]);
t3.setText(temp3);
else if (e.getSource() == b4) {
que1[3] = Integer.parseInt(t4.getText()) + 1;
String temp4 = String.valueOf(que1[3]);
t4.setText(temp4);
else if (e.getSource() == b5) {
que1[4] = Integer.parseInt(t5.getText()) + 1;
String temp5 = String.valueOf(que1[4]);
t5.setText(temp5);
} //end action performed
q2.addActionListener(
new ActionListener(){
public void actionPerformed( ActionEvent e )
{ //actionPerformed of all registered listeners
if (e.getSource() == b1) {
que2[0] = Integer.parseInt(t1.getText()) + 1;
String temp6 = String.valueOf(que2[0]);
t1.setText(temp1);
else if (e.getSource() == b2) {
que2[1] = Integer.parseInt(t2.getText()) + 1;
String temp7 = String.valueOf(que2[1]);
t2.setText(temp7);
else if (e.getSource() == b3) {
que2[2] = Integer.parseInt(t3.getText()) + 1;
String temp8 = String.valueOf(que2[2]);
t3.setText(temp8);
else if (e.getSource() == b4) {
que2[3] = Integer.parseInt(t4.getText()) + 1;
String temp9 = String.valueOf(que2[3]);
t4.setText(temp9);
else if (e.getSource() == b5) {
que2[4] = Integer.parseInt(t5.getText()) + 1;
String temp10 = String.valueOf(que2[4]);
t5.setText(temp10);
} //end action performed
q3.addActionListener(
new ActionListener(){
public void actionPerformed( ActionEvent e )
{ //actionPerformed of all registered listeners
if (e.getSource() == b1) {
que3[0] = Integer.parseInt(t1.getText()) + 1;
String temp11 = String.valueOf(que3[0]);
t1.setText(temp11);
else if (e.getSource() == b2) {
que3[1] = Integer.parseInt(t2.getText()) + 1;
String temp12 = String.valueOf(que3[1]);
t2.setText(temp12);
else if (e.getSource() == b3) {
que3[2] = Integer.parseInt(t3.getText()) + 1;
String temp13 = String.valueOf(que3[2]);
t3.setText(temp13);
else if (e.getSource() == b4) {
que3[3] = Integer.parseInt(t4.getText()) + 1;
String temp14 = String.valueOf(que3[3]);
t4.setText(temp14);
else if (e.getSource() == b5) {
que3[4] = Integer.parseInt(t5.getText()) + 1;
String temp15 = String.valueOf(que3[4]);
t5.setText(temp15);
} //end action performed
}//end constructor test
public void itemStateChanged(ItemEvent item) {
//int state = item.getStateChange();
//if (q1 == item.SELECTED)
public class ButtonPanel extends JPanel
public ButtonPanel()
public class CenterPanel extends JPanel
public CenterPanel()
public class QuestionPanel extends JPanel
public QuestionPanel()
public class ResponsePanel extends JPanel
public ResponsePanel()
public static void main(String [] args)
test surveyFrame = new test("Student Survey") ;
surveyFrame.setSize( 500,300 );
surveyFrame.setVisible(true);
surveyFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}//end main
}//end class testis not abstract and does not override abstract method actionPerformed
Oh, I see that the title of your post is an error message? Ok. Well, the test class is declared as implementing an ActionListener. That means the test class must have an actionPerformed() method. Your test class apparently does not.
It does not appear that the test class needs to implement ActionListener. You are using annonymous classes as listeners. -
Is not abstract and does not override abstract method ERROR
Hello. I'm new at all this, and am attempting to recreate a sample code out of my book (Teach Yourself XML in 24 Hours), and I keep getting an error. I appriciate any help.
This is the Error that I get:
DocumentPrinter is not abstract and does not override abstract method skippedEntity(java.lang.String) in org.xml.sax.ContentHandler
public class DocumentPrinter implements ContentHandler, ErrorHandler
^This is the sourcecode:
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class DocumentPrinter implements ContentHandler, ErrorHandler
// A Constant containing the name of the SAX parser to use.
private static final String PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
public static void main(String[] args)
// Check to see whether the user supplied any command line arguments. If not, print an error and exit.
if (args.length == 0)
System.out.println("No XML document path specified.");
System.exit(1);
// Create a new instance of the DocumentPrinter class.
DocumentPrinter dp = new DocumentPrinter();
try
// Create a new instance of the XML Parser.
XMLReader parser = (XMLReader)Class.forName(PARSER_NAME).newInstance();
// Set the parser's content handler
// parser.setContentHandler(dp);
// Set the parsers error handler
parser.setErrorHandler(dp);
// Parse the file named in the argument
parser.parse(args[0]);
catch (Exception ex)
System.out.println(ex.getMessage());
ex.printStackTrace();
public void characters(char[] ch, int start, int length)
String chars ="";
for (int i = start; i < start + length; i++)
chars = chars + ch;
System.out.println("Recieved characters: " + chars);
public void startDocument()
System.out.println("Start Document.");
public void endDocument()
System.out.println("End of Document.");
public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
System.out.println("Start element: " + localName);
for (int i = 0; i < atts.getLength(); i++)
System.out.println(" Attribute: " + atts.getLocalName(i));
System.out.println(" Value: " + atts.getValue(i));
public void endElement(String namespaceURI, String localName, String qName)
System.out.println("End of element: " + localName);
public void startPrefixMapping(String prefix, String uri)
System.out.println("Prefix mapping: " + prefix);
System.out.println("URI: " + uri);
public void endPrefixMapping(String prefix)
System.out.println("End of prefix mapping: " + prefix);
public void ignorableWhitespace(char[] ch, int start, int length)
System.out.println("Recieved whitespace.");
public void processingInstruction(String target, String data)
System.out.println("Recieved processing instruction:");
System.out.println("Target: " + target);
System.out.println("Data: " + data);
public void setDocumentLocation(Locator locator)
// Nada
public void error(SAXParseException exception)
System.out.println("Parsing error on line " + exception.getLineNumber());
public void fatalError(SAXParseException exception)
System.out.println("Fatal parsing error on line " + exception.getLineNumber());
public void warning(SAXParseException exception)
System.out.println("Warning on line " + exception.getLineNumber());Check to make sure that the arguments are consistent with your ContentHandler class. Probably the wrong type.
I think you forgot to include the skippedEntity method, it seems to be missing. Even if an implemented class has a method that you are not using, you still have to include the method in your code even if it doesn't do anything.
Message was edited by:
ChargersTule1 -
I have a series of questions....... Go through.
What is the use of abstract interface in java ?
What is the use of static object in java ?
What is the use of abstract key word to variables ?
Object reference passed to method are final. Can ' t we change it ?class Testing {
int i;
public class RefFinal {
public static void f ( Testing t1, Testing t2) {
Testing temp;
temp=t1;
t1=t2;
t2=temp;
System.out.println("value of i in t1 =" +t1.i);
System.out.println("value of i in t2 =" +t2.i);
public static void main( String args[]) {
Testing t1 = new Testing();
Testing t2 = new Testing();
t1.i=10;
t2.i=20;
f(t1,t2);
System.out.println("value of i in t1 =" +t1.i);
System.out.println("value of i in t2 =" +t2.i);
} Here the code explain why? -
Product is not abstract and does not override abstract method
Received the following errors.
Product.java:3: Product is not abstract and does not override abstract method ge
tDisplayText() in Displayable
public class Product implements Displayable
^
Product.java:16: getDisplayText() in Product cannot implement getDisplayText() i
n Displayable; attempting to use incompatible return type
found : void
required: java.lang.String
public void getDisplayText()
^
2 errors
Code reads as follows
import java.text.NumberFormat;
public class Product implements Displayable
private String code;
private String description;
private double price;
public Product()
this.code = "";
this.description = "";
this.price = 0;
public void getDisplayText()
String message =
"Code: " + code + "\n" +
"Description: " + description + "\n" +
"Price: " + this.getFormattedPrice() + "\n";
public Product(String code, String description, double price)
this.code = code;
this.description = description;
this.price = price;
public void setCode(String code)
this.code = code;
public String getCode(){
return code;
public void setDescription(String description)
this.description = description;
public String getDescription()
return description;
public void setPrice(double price)
this.price = price;
public double getPrice()
return price;
public String getFormattedPrice()
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
Please help!Received the following errors.
Product.java:3: Product is not abstract and does not
override abstract method ge
tDisplayText() in Displayable
public class Product implements Displayable
^
Product.java:16: getDisplayText() in Product cannot
implement getDisplayText() i
n Displayable; attempting to use incompatible return
type
found : void
required: java.lang.String
public void getDisplayText()
^
2 errors
Code reads as follows
Please use the code tags when posting code. There is a code button right above the text box where you enter your post. Click on it and put the code between the code tags.
These error messages are quite clear in telling what is wrong. You have an Interface called Displayable that specifies a method something like thispublic String getDisplayText() {But in your Product source code, you created thismethodpublic void getDisplayText() {The compiler is complaining because the methods are not the same.
You also need to return a String in the method probalby like thisreturn message; -
Abstract method called in an abstract class
Hello,
I am writing some code that I'd like to be as generic as possible.
I created an abstract class called Chromozome. This abstract class has a protected abstract method called initialize().
I also created an abstract class called Algorithm which contains a protected ArrayList<Chromozome>.
I would like to create a non abstract method (called initializePopulation()) which would create instances of Chromozome, call their method initialize() and full the ArrayList with them.
In a practical matter, only subclass of Algorithm will be used, using an ArrayList of a subclass of Chromozome implementing their own version of initialize.
I have been thinking of that and concluded it was impossible to do. But I'd like to ask more talented peaple before forgetting it !
Thanks,
VincentOk, let's it is not impossible, juste that I had no idea of how doing it :-)
The difficulty is that Algorithm will never have to deal with Chromozome itself, but always with subclass of Chromozome. This is usually not an issue, but in that case, Algorithm is required to create instances of the desired subclass of Chromozome, but without knowing in advance wich subclass will be used (I hope what I say makes any sense).
Actually I may have found a way in the meantime, but maybe not the best one.
I created in Algorithm an abstract method :
protected abstract Chromozome createChromozome()The method initializePopulation will call createChromozome instead of calling directly the constructor and the initialize() method of Chromozome.
Then subclass of Algorithm will implement the method createChromozome using the desired subclass of Chromozome. -
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 -
Abstract Method Error and XML Parsing
I am using wl6sp1. I am parsing an XML file from within the
servlet using jaxp1.1 and crimson.
Following is code:
1- SAXParserFactory spf = SAXParserFactory.newInstance();
2- sp = spf.newSAXParser();
3- xr = sp.getXMLReader();
4- xr.setContentHandler(new ParseXML());
5- xr.parse( new InputSource("Example3.xml"));
This program works fine when execute from command line but in servlet on line
3 it says:
"Abstract Method Error"
I have created XML Registry to use Crimson as XML parser rather than default.
I think somehow wl is still using jaxp1.0 which is built in
support in wlsp1.
Whats wrong with the code...or what configuration i am missing???I'm assuming you have already put crimson.jar first in the classpath for the java
command you use to start WebLogic. If so, have you tried putting the servlet in
a .war file with the crimson.jar in its' WEB-INF/lib directory?
Regards,
Mike Wooten
"anyz" <[email protected]> wrote:
>
I am using wl6sp1. I am parsing an XML file from within the
servlet using jaxp1.1 and crimson.
Following is code:
1- SAXParserFactory spf = SAXParserFactory.newInstance();
2- sp = spf.newSAXParser();
3- xr = sp.getXMLReader();
4- xr.setContentHandler(new ParseXML());
5- xr.parse( new InputSource("Example3.xml"));
This program works fine when execute from command line but in servlet
on line
3 it says:
"Abstract Method Error"
I have created XML Registry to use Crimson as XML parser rather than
default.
I think somehow wl is still using jaxp1.0 which is built in
support in wlsp1.
Whats wrong with the code...or what configuration i am missing???
Maybe you are looking for
-
My apple id is with gmail, I want to change it and create an @me email address. How can I do this?, My apple id is with gmail, I want to change it and create an @me email address. How can I do this?
-
Sharepoint 2010 - Error while running Configuration wizard for SP 2010 server farm
Hi All, I am trying to set up a SP 2010 farm. I have windows server 2008 R2 installed and was able to install SP 2010 successfully. However when I ran the Sp 2010 Products and configuration wizard I am getting the following error at Step 3. Failed t
-
Role info not appearing once role assignment request is submitted from UI
Hi Everyone, We have a strange problem in our project in IDM 7.2 SP8 where IDM role concept is used which contains privileges (could be role/profile) of backend systems. Usually when ever a role (i.e IDM role) assignment request is submitted from UI,
-
Problem downloading FlashPlayer 11; stops at 50%; Error
FlashPlayer 11 Downloading stops at about 50%, then displays "Error: General Installation Error" Nothing seems to work. Turned off Virus Protection, Both 'Scripting settings are already set to Enabled, OS is WinXP and IE8 is being used in Compatibil
-
Can't create second caldav account
I have a work calendar that I have successfully synced with google and embedded on my website. Now I would like to sync a second calendar for family stuff. But every time I try to create a second caldav account in iCal, nothing happens! I need a seco