Abstract method in constructor
Hi!
This is simplification of my 'problem'. I solved it by more clear approach but I still don't understand the result. Output is: true, false, true. I would expect true, true, true. I use Mac Java 1.4.1.
public class TestAbstract {
public static void main(String[] args) {
boolean empty=true;
final boolean isEmpty=empty;
System.out.println(isEmpty);
Abstract a = new Abstract(new Integer(10)) {
public String getInitValue(Object value) {
Integer i=(Integer)value;
System.out.println(isEmpty);
return(isEmpty?String.valueOf(i):"");
public void setValue(Object value) {
System.out.println(isEmpty);
a.x();
public static abstract class Abstract {
private Object value;
private String s;
public Abstract(Object _value) {
value=_value;
s=getInitValue(value);
public void x() {
setValue(value);
public abstract String getInitValue(Object value);
public abstract void setValue(Object value);
Wierd. I get
true
true
true
on winXP 1.4.1 and 1.5.0 beta
Similar Messages
-
Calling abstract method inside constructor
what will happen if you call abstract method inside a constructor ?
AMARSHI wrote:
Then wat is the purpose of that object then.
When u create an object then the control will move to the default constructor,If there is one. Not all classes have default constructors. Some c'tor will be called though.
inside the constructor u r having an abstract method.
But theere are 2 cases now:
1 the top-level class is an abstract class
2 the abstract class is an inner class.
1. for case 1 , u cannot create an object ,so no need of having the constructor.Yes, you can create an object. You can instantiate a concrete subclass. The abstract parent's constructor is still called, and that c'tor may call an abstract method, which will be implemented in the concrete subclass, or some class between it and the parent.
2.for case 2 u cannot have an object like:
outerClass obj = new innerAbstractClass()I have no idea what you're talking about here. -
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. -
Abstract classes and constructors - cannot call abs. methods in CONSTRUCTOR
Let me explain the scenario:
I'm building a program in which I need to read a file (among other things) and I intend to use object orientation to it's fullest in doing so. I thought of creating an abstract FILE class which has the commonalities, and two subclasses SERVER_FILE and PC_FILE, which implement the abstract method GET_CONTENTS in different ways (OPEN DATASET / GUI_UPLOAD), same for the CHOOSE method which allows to select the file from it's corresponding source.
Initially I've used an interface but since another tasks like setting the file path are common for both, switched to an ABSTRACT class.
Now, the problem is, from the main code I intend to use a FILE reference to handle either type of file. At the instantiation moment I'd like the path attribute to be set; if it was not set by parameter, i'd like to call the CHOOSE method which is abstract for the superclass. Since this is common for either subclass, I need a way to code it once in the superclass. But I get an error because the CHOOSE method is abstract.
This is the problem code (extracts):
* CLASS lcl_file DEFINITION
CLASS lcl_file DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING
i_path TYPE string OPTIONAL
EXCEPTIONS
no_path_chosen,
get_contents ABSTRACT
RETURNING
value(rt_contents) TYPE string_table
EXCEPTIONS
read_error.
PROTECTED SECTION.
DATA:
_v_path TYPE string.
METHODS:
choose ABSTRACT
EXCEPTIONS
no_path_chosen,
set_path
IMPORTING
i_path TYPE string.
ENDCLASS. "lcl_file DEFINITION
* CLASS lcl_file IMPLEMENTATION
CLASS lcl_file IMPLEMENTATION.
METHOD constructor.
IF i_path IS SUPPLIED.
CALL METHOD set_path
EXPORTING
i_path = i_path.
ELSE.
*---->>>> PROBLEM CALL - CAN'T BE DONE!!
CALL METHOD choose
EXCEPTIONS
no_path_chosen = 1.
IF sy-subrc = 1.
RAISE no_path_chosen.
ENDIF.
ENDIF.
ENDMETHOD. "constructor
METHOD set_path.
_v_path = i_path.
ENDMETHOD. "set_path
ENDCLASS. "lcl_file IMPLEMENTATION
* CLASS lcl_server_file DEFINITION
CLASS lcl_server_file DEFINITION
INHERITING FROM lcl_file.
PUBLIC SECTION.
METHODS:
get_contents REDEFINITION.
PROTECTED SECTION.
METHODS:
choose REDEFINITION.
ENDCLASS. "lcl_server_file DEFINITIO
* CLASS lcl_server_file IMPLEMENTATION
CLASS lcl_server_file IMPLEMENTATION.
METHOD choose.
DATA:
l_i_path TYPE dxfields-longpath,
l_o_path TYPE dxfields-longpath.
CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
EXPORTING
i_location_flag = 'A' " Application server
i_path = l_i_path
fileoperation = 'R' " Lectura
IMPORTING
o_path = l_o_path
EXCEPTIONS
rfc_error = 1
OTHERS = 2.
IF sy-subrc = 0 AND l_o_path <> l_i_path.
MOVE l_o_path TO _v_path.
ELSE.
RAISE no_path_chosen.
ENDIF.
ENDMETHOD. "choose
METHOD get_contents.
DATA: l_line LIKE LINE OF rt_contents,
l_osmsg TYPE string.
CHECK NOT _v_path IS INITIAL.
OPEN DATASET _v_path FOR INPUT
IN TEXT MODE
MESSAGE l_osmsg.
IF sy-subrc <> 0.
MESSAGE e000(oo) WITH l_osmsg
RAISING read_error.
ELSE.
DO.
READ DATASET _v_path INTO l_line.
IF sy-subrc = 0.
APPEND l_line TO rt_contents.
ELSE.
EXIT.
ENDIF.
ENDDO.
CLOSE DATASET _v_path.
ENDIF.
ENDMETHOD. "get_contents
ENDCLASS. "lcl_server_file IMPLEMENTATION
* CLASS lcl_pc_file DEFINITION
CLASS lcl_pc_file DEFINITION
INHERITING FROM lcl_file.
PUBLIC SECTION.
METHODS:
get_contents REDEFINITION.
PROTECTED SECTION.
METHODS:
choose REDEFINITION.
ENDCLASS. "lcl_pc_file DEFINITIO
* CLASS lcl_pc_file IMPLEMENTATION
CLASS lcl_pc_file IMPLEMENTATION.
METHOD choose.
DATA:
l_i_path TYPE dxfields-longpath VALUE 'C:\',
l_o_path TYPE dxfields-longpath.
CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
EXPORTING
i_location_flag = 'P' " PC
i_path = l_i_path
fileoperation = 'R' " Lectura
IMPORTING
o_path = l_o_path
EXCEPTIONS
rfc_error = 1
OTHERS = 2.
IF sy-subrc = 0 AND l_o_path <> l_i_path.
MOVE l_o_path TO _v_path.
ELSE.
RAISE no_path_chosen.
ENDIF.
ENDMETHOD. "choose
METHOD get_contents.
CHECK NOT _v_path IS INITIAL.
CALL METHOD cl_gui_frontend_services=>gui_upload
EXPORTING
filename = _v_path
CHANGING
data_tab = rt_contents
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
OTHERS = 17.
IF sy-subrc <> 0.
RAISE read_error.
ENDIF.
ENDMETHOD. "get_contents
ENDCLASS. "lcl_pc_file IMPLEMENTATION
* Data
DATA: gr_file TYPE REF TO lcl_file.
* Main Program
START-OF-SELECTION.
* Get text lines from file
IF p_srv = abap_true.
CREATE OBJECT gr_file
TYPE
lcl_server_file
EXCEPTIONS
no_path_chosen = 1.
ELSE.
CREATE OBJECT gr_file
TYPE
lcl_pc_file
EXCEPTIONS
no_path_chosen = 1.
ENDIF.
On a 4.6c system this code gave me a dump, while on my NW7.0 SP it doesn't even activate with the following error:
You cannot call abstract methods in the "CONSTRUCTOR" method.
- Following some suggestions from Java forums i've tried to define the constructor in the base class as PROTECTED or PRIVATE instead, then calling super->constructor from the subclasses, but I get this error in german:
Sichtbarkeit des Konstruktors darf nicht spezieller als die Sichtbarkeit der Instanzerzeugung (CREATE-Zuzatz) sein.
which Altavista translates like:
Visibility of the constructor may not be more special than the
visibility of the instance production (CREATE Zuzatz).
- I've also thought of defining the CHOOSE method as a class (not instance) one, then calling it before creating the file object which maybe solves the problem, but I see that approach more "procedural oriented" which i'm trying to avoid.
- Of course I could define a constructor for each subclass, but both would have exactly the same code.
I'm really lost on how should I code this. My main focus is on avoiding code dupplication.
I hope someone with more OO experience can see what I'm trying to do and sheds some light.
Many thanks for reading all this!Dear Alejandro,
When i saw your code, you are trying to access an astract method CHOOSE(which is actually implemented in sub class) from the constructor of the base class which is not possible. By this time, we don't know which sub class it is refering to, so it gives an error. I see two solutions for this..
1. To define constructor in sub class and call the choose method from the consturctor of the sub class(which in this case is reputation of the same again for each sub class)
2. Remove the calling of choose method from the constructor of the main class and call it separately(after creating the object). By now we know which sub class we are refering to. I would have designed the program in the following way.
* CLASS lcl_file DEFINITION
CLASS lcl_file DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS:
constructor
IMPORTING
i_path TYPE string OPTIONAL
EXCEPTIONS
no_path_chosen,
get_contents ABSTRACT
RETURNING
value(rt_contents) TYPE string_table
EXCEPTIONS
read_errorm,
set_path ABSTRACT
EXCEPTIONS
no_path_chosen.
PROTECTED SECTION.
DATA:
_v_path TYPE string.
* METHODS:
* choose ABSTRACT
* EXCEPTIONS
* no_path_chosen,
* set_path ABSTRACT
* IMPORTING
* i_path TYPE string.
ENDCLASS. "lcl_file DEFINITION
* CLASS lcl_file IMPLEMENTATION
CLASS lcl_file IMPLEMENTATION.
METHOD constructor.
IF i_path IS SUPPLIED.
_v_path = i_path.
* CALL METHOD set_path
* EXPORTING
* i_path = i_path.
* ELSE.
**---->>>> PROBLEM CALL - CAN'T BE DONE!!
* CALL METHOD choose
* EXCEPTIONS
* no_path_chosen = 1.
* IF sy-subrc = 1.
* RAISE no_path_chosen.
* ENDIF.
ENDIF.
ENDMETHOD. "constructor
* METHOD set_path.
* _v_path = i_path.
* ENDMETHOD. "set_path
ENDCLASS. "lcl_file IMPLEMENTATION
* CLASS lcl_server_file DEFINITION
CLASS lcl_server_file DEFINITION
INHERITING FROM lcl_file.
PUBLIC SECTION.
METHODS:
get_contents REDEFINITION,
set_path REDEFINITION.
* PROTECTED SECTION.
* METHODS:
* choose REDEFINITION.
ENDCLASS. "lcl_server_file DEFINITIO
* CLASS lcl_server_file IMPLEMENTATION
CLASS lcl_server_file IMPLEMENTATION.
METHOD set_path.
DATA:
l_i_path TYPE dxfields-longpath,
l_o_path TYPE dxfields-longpath.
CHECK _v_path IS INITIAL.
CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
EXPORTING
i_location_flag = 'A' " Application server
i_path = l_i_path
fileoperation = 'R' " Lectura
IMPORTING
o_path = l_o_path
EXCEPTIONS
rfc_error = 1
OTHERS = 2.
IF sy-subrc = 0 AND l_o_path = l_i_path.
MOVE l_o_path TO _v_path.
ELSE.
RAISE no_path_chosen.
ENDIF.
ENDMETHOD. "set_path
METHOD get_contents.
DATA: l_line LIKE LINE OF rt_contents,
l_osmsg TYPE string.
CHECK NOT _v_path IS INITIAL.
* OPEN DATASET _v_path FOR INPUT
* IN TEXT MODE
* MESSAGE l_osmsg.
IF sy-subrc = 0.
* MESSAGE e000(oo) WITH l_osmsg
* RAISING read_error.
ELSE.
DO.
READ DATASET _v_path INTO l_line.
IF sy-subrc = 0.
APPEND l_line TO rt_contents.
ELSE.
EXIT.
ENDIF.
ENDDO.
CLOSE DATASET _v_path.
ENDIF.
ENDMETHOD. "get_contents
ENDCLASS. "lcl_server_file IMPLEMENTATION
* CLASS lcl_pc_file DEFINITION
CLASS lcl_pc_file DEFINITION
INHERITING FROM lcl_file.
PUBLIC SECTION.
METHODS:
get_contents REDEFINITION,
set_path REDEFINITION.
* PROTECTED SECTION.
* METHODS:
* choose REDEFINITION.
ENDCLASS. "lcl_pc_file DEFINITIO
* CLASS lcl_pc_file IMPLEMENTATION
CLASS lcl_pc_file IMPLEMENTATION.
METHOD set_path.
DATA:
l_i_path TYPE dxfields-longpath VALUE 'C:\',
l_o_path TYPE dxfields-longpath.
CHECK _v_path IS INITIAL.
CALL FUNCTION 'F4_DXFILENAME_TOPRECURSION'
EXPORTING
i_location_flag = 'P' " PC
i_path = l_i_path
fileoperation = 'R' " Lectura
IMPORTING
o_path = l_o_path
EXCEPTIONS
rfc_error = 1
OTHERS = 2.
IF sy-subrc = 0 AND l_o_path = l_i_path.
MOVE l_o_path TO _v_path.
ELSE.
RAISE no_path_chosen.
ENDIF.
ENDMETHOD. "set_path
METHOD get_contents.
CHECK NOT _v_path IS INITIAL.
CALL METHOD cl_gui_frontend_services=>gui_upload
EXPORTING
filename = _v_path
CHANGING
data_tab = rt_contents
EXCEPTIONS
file_open_error = 1
file_read_error = 2
no_batch = 3
gui_refuse_filetransfer = 4
invalid_type = 5
no_authority = 6
unknown_error = 7
bad_data_format = 8
header_not_allowed = 9
separator_not_allowed = 10
header_too_long = 11
unknown_dp_error = 12
access_denied = 13
dp_out_of_memory = 14
disk_full = 15
dp_timeout = 16
OTHERS = 17.
IF sy-subrc = 0.
* RAISE read_error.
ENDIF.
ENDMETHOD. "get_contents
ENDCLASS. "lcl_pc_file IMPLEMENTATION
* Data
DATA: gr_file TYPE REF TO lcl_file.
* Main Program
START-OF-SELECTION.
* Get text lines from file
IF abap_true = abap_true.
CREATE OBJECT gr_file
TYPE
lcl_server_file
EXCEPTIONS
no_path_chosen = 1.
ELSE.
CREATE OBJECT gr_file
TYPE
lcl_pc_file
EXCEPTIONS
no_path_chosen = 1.
ENDIF.
gr_file->set_path( ).
Regards
Kesava
Edited by: Kesava Chandra Rao on Mar 19, 2008 11:44 AM -
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. -
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. -
Hi all,
In SE24 i made an abstract class & made a method abstract successfully.
Now i made another class that inherited my abstract class, it is showing my abstract method there.
Now when i want to give implementation to that method, but when i double click on that system is showing "method is abstract & has not yet redefined".
Pleas let me know..how i implement it..
Thanx in advance..
<b>Have ur point.s</b>Hi
Inheritance Inheritance defines the implementation relationship between classes, in which one class (the subclass) shares the structure and the behavior defined in one or more other classes (superclasses). Note: ABAP Objects only allows single inheritance.
Inheritance is a relationship, in which one class (the subclass) inherits all the main characteristics of another class (the superclass). The subclass can also add new components (attributes, methods, and so on) and replace inherited methods with its own implementations.
<b>Single Inheritance</b>
ABAP Objects only has single inheritance.
A class may only have one direct superclass, but it can have more than one direct subclass. The empty class OBJECT is the root node of every inheritance tree in ABAP Objects.
<b>Relationship between Superclasses and Subclasses</b>
Common components only exists in the superclass
new components in the supercalss are automatically available in subclass
amount of new coding is reduced ( programing by difference)
Subclass are extremely dependent on superclases
white box reuse subclass must possess detailed knowledge of the implementation of the superclass
<b>Inheritance: Syntax</b>
Normally the only other entry required for subclasses is what has changed in relation to the direct superclass. Only additions are permitted in ABAP Objects, that is, in a subclass you can "never take something away from a superclass". All components from the superclass are automatically present in the subclass.
<b>Class name defination.
public section.
methods. First name importing some type some type
returning value(value) type some type.
private section
data : make type string..
Endclass.
Class name1 definition inheriting name
public section
method. : get returning value ( value) type get.
Priavte section.
data : max type some type
endclass</b>
<b> Redefining methods</b>
The REDEFINITION statement for the inherited method must be in the same SECTION as the definition of the original method.
If you redefine a method, you do not need to enter its interface again in the subclass, but only the name of the method.
In the case of redefined methods, changing the interface (overloading) is not permitted; exception: Overloading is possible with the constructor.
Within the redefined method, you can access components of the direct superclass using the SUPER reference.
The pseudo-reference super can only be used in redefined methods.
reward if usefull -
Hello developers,
I am trying to implement the following (simple) classes:
class abstract_class definition abstract
public
create public .
protected section
methods parse_string abtract
importing
value(i_str) type string.
methods to_table.
endclass.
class abstract_class implementation.
method to_table.
me->parse_string( str ).
endmethod.
endclass.
class other_class definition
public
inheriting from abstract_class
final
create public .
protected section.
methods parse_string redefinition.
endclass.
class other_class implementation.
method parse_string.
* some codes
endmethod.
endclass.
I have instantiated the class other_class. But when I call the method to_table, I am getting the error "CALL METHOD NOT IMPLEMENTED" on the method parse_string. Where is my mistake ?
Thank you for your replies.
Best regards,
NicolasHello everyone,
First of all, thank you for all your reply.
During the night, I have thought to my problem and I found the solution. In fact, I made a (very) great mistake. Here is my code:
CLASS abstract_class IMPLEMENTATION.
method constructor.
me->to_table( ).
endmethod.
method to_table.
me->parse_string( a_string ).
endmethod.
ENDCLASS.
CLASS other_class IMPLEMENTATION.
method constructor.
call method super->constructor.
endmethod.
method parse_string.
* some code
endmethod.
ENDCLASS.
The problem is: I call the method parse_string of my child class (with the instruction me->parse_string) before my child class is instantiated... (Now, I can jump out the window.) Vadim Vologzhanin 's reply helped me by asking where I instantiated my child class.
Thank you !
Best regards,
Nicolas -
Abstract Methods and Override Don't work For SubPackages
I have an abstract class called "A" in a package called test.
package test;
public abstract class A
int x;
public A (int x)
this.x = x;
abstract void testMethod();
}And I have a sub class of "A" called "SubA" in a sub package of "test" called "test.subPkg":
package test.subPkg;
import test.A;
public class SubA extends A {
public SubA(int x)
super(x);
@Override
void testMethod()
throw new UnsupportedOperationException("Not supported yet.");
}Now when I try to compile, it gives me the error:
/home/eric/NetBeansProjects/drum-tabber4/trunk/src/test/subPkg/SubA.java:6: test.subPkg.SubA is not abstract and does not override abstract method testMethod() in test.A
public class SubA extends A {
/home/eric/NetBeansProjects/drum-tabber4/trunk/src/test/subPkg/SubA.java:14: method does not override or implement a method from a supertype
If I put SubA in the above package "test" instead of "test.subPkg", it compiles fine. But I don't want to do that because I have a lot of sub classes that are organized differently in separate sub packages.
If I make A an interface, it compiles fine. But I don't want to do that either because I want A to implement the constructor.
Anyone have any idea of how to fix this issue?Now when I try to compile, it gives me the error:
/home/eric/NetBeansProjects/drum-tabber4/trunk/src/test/subPkg/SubA.java:6: test.subPkg.SubA is not abstract and does not override abstract method testMethod() in test.A
public class SubA extends A {
/home/eric/NetBeansProjects/drum-tabber4/trunk/src/test/subPkg/SubA.java:14: method does not override or implement a method from a supertype
If I put SubA in the above package "test" instead of "test.subPkg", it compiles fine. But I don't want to do that because I have a lot of sub classes that are organized differently in separate sub packages.Thats because method testMethod() in class A has a default access modifier. Meaning, that testMethod() will only be visible within the same package and not outside of package test. Expand the access modifier of testMethod() in class A, either make it protected or public, like this...
protected abstract void testMethod();
OR
public abstract void testMethod(); -
Hello guys,
I have a LPQueue class that implements a interface PQueue
Here are the fiels:
//PQueue interface
import java.util.Iterator;
interface PQueue<E extends Comparable<E>>
public void insert(E x);
public E peekMax();
public E deleteMax();
public int size();
public void clear();
public Iterator<E> iterator();
//LPQueue class
import java.util.*;
import java.util.Iterator;
public class LPQueue<E extends Comparable<E>> implements PQueue<E>
private Node<E> first;
private int size;
public LPQueue(){
first = null; //pointing to the first element
size = 0;
public void insert(E x){
Node <E> tmp = new Node<E>(x);
size++; //when we call insert we want to increase size by one to keep the size of queue current
Node <E> p = first; //p points to first element
Node <E> q = null; //this points to null initially because q has to stay behind p
while(p != null && x.compareTo(p.data) > 0){
q = p;
p = p.next;
if(q == null){
tmp.next = first;
first = tmp;
else{
tmp.next = p;
q.next = tmp;
public E peekMax(E x){
if(size == 0){
throw new NoSuchElementException();
if(x.compareTo(first.data) > 0){
return x;
}else return first.data;
public E deleteMax(E x){
Node <E> tmp;
if(size == 0){
throw new NoSuchElementException();
if(x.compareTo(first.data) > 0){
first.data = null;
return x;
}else
tmp = first;
first.data = null;
return tmp.data;
public int size(){
return size;
public void clear(){
size = 0;
first = null;
public Iterator<E> iterator()
return new LQIterator();
private class LQIterator implements Iterator<E>{
public Node<E> current;
private LQIterator()
current = first;
public boolean hasNext()
return current !=null;
public E next()
if(!hasNext()){
throw new NoSuchElementException();
E x = current.data;
current = current.next;
return x;
public void remove()
throw new UnsupportedOperationException();
//seting up static Node class
private static class Node <E>{
public E data; //seting up paramtere data for node
public Node<E> next; //
public Node(E x){ //sting up constructor for Node passing the paramter x to data
data = x;
}When i try to compile i get :
The type LPQueue<E> must implement the inherited abstract method PQueue<E>.deleteMax() LPQueue.java
The type LPQueue<E> must implement the inherited abstract method PQueue<E>.peekMax() LPQueue.java
I have written the definition for both the peekMax and deletMax methods why am i still getting the above error?
Thank you for your help,
-LovacThe method signatures of the interface must match up exactly with the implementing classes. In the interface, neither method signature accepted a parameter, but in your concrete class, they do, and this just won't work.
-
Is not abstract and does not override abstract method tablechanged
I will remove all the gui code to make it shorter, but my problem lies with my InteractiveTableModelListener.
public class Meet extends JPanel{
private static void createAndShowGUI() {
JFrame frame = new JFrame("MEET_dataTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Meet(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
public class InteractiveTableModelListener implements TableModelListener {
public void TableChanged(TableModelEvent evt) {
if (evt.getType() == TableModelEvent.UPDATE) {
int column = evt.getColumn();
int row = evt.getFirstRow();
dataTable.setColumnSelectionInterval(column + 1, column + 1);
dataTable.setRowSelectionInterval(row, row);
class InteractiveRenderer extends DefaultTableCellRenderer {
protected int interactiveColumn;
public InteractiveRenderer(int interactiveColumn) {
this.interactiveColumn = interactiveColumn;
public Component getTableCellRendererComponent(JTable dataTable,
Object value, boolean isSelected, boolean hasFocus, int row,
int column)
Component c = super.getTableCellRendererComponent(dataTable, value, isSelected, hasFocus, row, column);
if (column == interactiveColumn && hasFocus) {
if ((Meet.this.tableModel.getRowCount() - 1) == row &&
!Meet.this.tableModel.hasEmptyRow())
Meet.this.tableModel.addEmptyRow();
highlightLastRow(row);
return c;
public void highlightLastRow(int row) {
int lastrow = tableModel.getRowCount();
if (row == lastrow - 1) {
dataTable.setRowSelectionInterval(lastrow - 1, lastrow - 1);
else {
dataTable.setRowSelectionInterval(row + 1, row + 1);
dataTable.setColumnSelectionInterval(0, 0);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}As i say, i have removed all the gui code to make it shorter, but in this code i create the table and add all the model to it. I am being returned with the error
Meet.InteractiveTableModelListener is not abstract and does not override abstract method tableChanged(javax.swing.event.TableModelEvent)in javax.swing.event.TableModelListener
what would be causing this error?
CheersSorry, just figured out my silly error, the method is tableChanged not TableChanged.
cheers
TOPIC CLOSED
Edited by: nick2price on Sep 11, 2008 7:08 AM -
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 -
...is not abstract and does not override abstract method compare
Why am I getting the above compile error when I am very clearly overriding abstract method compare (ditto abstract method compareTo)? Here is my code -- which was presented 1.5 code and I'm trying to retrofit to 1.4 -- followed by the complete compile time error. Thanks in advance for your help (even though I'm sure this is an easy question for you experts):
import java.util.*;
This program sorts a set of item by comparing
their descriptions.
public class TreeSetTest
public static void main(String[] args)
SortedSet parts = new TreeSet();
parts.add(new Item("Toaster", 1234));
parts.add(new Item("Widget", 4562));
parts.add(new Item("Modem", 9912));
System.out.println(parts);
SortedSet sortByDescription = new TreeSet(new
Comparator()
public int compare(Item a, Item b) // LINE CAUSING THE ERROR
String descrA = a.getDescription();
String descrB = b.getDescription();
return descrA.compareTo(descrB);
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
An item with a description and a part number.
class Item implements Comparable
Constructs an item.
@param aDescription the item's description
@param aPartNumber the item's part number
public Item(String aDescription, int aPartNumber)
description = aDescription;
partNumber = aPartNumber;
Gets the description of this item.
@return the description
public String getDescription()
return description;
public String toString()
return "[descripion=" + description
+ ", partNumber=" + partNumber + "]";
public boolean equals(Object otherObject)
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Item other = (Item) otherObject;
return description.equals(other.description)
&& partNumber == other.partNumber;
public int hashCode()
return 13 * description.hashCode() + 17 * partNumber;
public int compareTo(Item other) // OTHER LINE CAUSING THE ERROR
return partNumber - other.partNumber;
private String description;
private int partNumber;
}Compiler error:
TreeSetTest.java:25: <anonymous TreeSetTest$1> is not abstract and does not over
ride abstract method compare(java.lang.Object,java.lang.Object) in java.util.Com
parator
public int compare(Item a, Item b)
^
TreeSetTest.java:41: Item is not abstract and does not override abstract method
compareTo(java.lang.Object) in java.lang.Comparable
class Item implements Comparable
^
2 errorsAccording to the book I'm reading, if you merely take
out the generic from the code, it should compile and
run in v1.4 (assuming, of course, that the class
exists in 1.4). I don't know what book you are reading but that's certainly incorrect or incomplete at least. I've manually retrofitted code to 1.4, and you'll be inserting casts as well as replacing type references with Object (or the erased type, to be more precise).
These interfaces do exist in 1.4, and
without the generics.Exactly. Which means compareTo takes an Object, and you should change your overriding method accordingly.
But this raises a new question: how does my 1.4
compiler know anything about generics? It doesn't and it can't. As the compiler is telling you, those interfaces expect Object. Think about it, you want to implement one interface which declares a method argument type of Object, in several classes, each with a different type. Obviously all of those are not valid overrides. -
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; -
Getting error while creating abstract method
hi folks,
i facing issue for ABSTRACT Class.
I am trying to create abstarct method, (refered example from saptechnical site),
I created one attribute i-num, created one method AREA, in implementation area , i made it as Abstract, then i did syntax check, then it is giving below error.
*Class ZTEST_CLASS01_AB,Method AREA
The abstract method "AREA" can only be implemented after its
redefinition (METHODS AREA REDEFINITION).*
i tried all the ways..
created subclass for this, i writted some code in AREA of Sub-class, there it is giving dump, because first one is not activated properly..
could you please somebody help me on this.
SriHello Arshad,
Create a class(ZABSTRACT) and make its type as Abstract( Which means atleast one of its methods is abstract)
We can have abstract classes with all it's methods as non-abstract or concrete. A small example is given below:
CLASS gcl_abstract DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS concrete. "Concrete
ENDCLASS. "gcl_abstract DEFINITION
* CLASS gcl_abstract IMPLEMENTATION
CLASS gcl_abstract IMPLEMENTATION.
METHOD concrete.
WRITE: / `I'm a concrete method`.
ENDMETHOD. "concrete
ENDCLASS. "gcl_abstract IMPLEMENTATION
* CLASS gcl_abstract_sub DEFINITION
CLASS gcl_abstract_sub DEFINITION INHERITING FROM gcl_abstract.
PUBLIC SECTION.
METHODS concrete REDEFINITION.
ENDCLASS. "gcl_abstract_sub DEFINITION
* CLASS gcl_abstract_sub IMPLEMENTATION
CLASS gcl_abstract_sub IMPLEMENTATION.
METHOD concrete.
super->concrete( ).
WRITE: / 'Abstract class might not have abstract methods at all!'.
ENDMETHOD. "concrete
ENDCLASS. "gcl_abstract_sub IMPLEMENTATION
START-OF-SELECTION.
DATA: go_abstract TYPE REF TO gcl_abstract_sub.
CREATE OBJECT go_abstract.
go_abstract->concrete( ).
Although i will agree there is no point in making a class as abstract & having no abstract method
@Sri: Looks like you're trying to implement the abstract method "AREA" in the abstract class hence the error. For abstract method you cannot define their implementation in the corres. abstract class.
BR,
Suhas
Edited by: Suhas Saha on Mar 30, 2011 12:04 PM
Maybe you are looking for
-
Single concurrent program for multiple operating units
HI I am working on XML/BI publisher to generate AR invoice reports. We have single rdf report using which rtf templates are generated. There are 10 operating units (10 ORG_ID's) and 10 rtf templates, one for each operating unit. There are 4 different
-
How do I find 100 gigs of "photos"?
When I go to "About this Mac", and then to "Storage" I find that I have nearly 200 gigs of photos on my hard drive. However, all the photos I need/want are under "Pictures", in a few folders. When I "Get Info" about those folders, I find I have about
-
Auto Update of measuring point/document
Dear all, I have one issue over here.Measuring point/document is not updating automatically after productiuon order confirmation . I tried with following steps 1) Created the equipment as test equipment -->created measuring point as a counter ---> ma
-
Hi, I keep getting an error msg 1051 when texting to short code 71441. I checked with Sprint & there is no block on any of my messaging and all my settings are correct on my phone, everything is updated. I receive all other text messages regular & sh
-
E26 253 Error while check in only while running FM
Dear Experts, I am trying to run Function module BAPI_DOCUMENT_CHECKIN2, which is returning with the error message E 26 253 Error while check in and storing: D:\ XXX (Path) \XXX (file name). I have entered the following required input. DOCUMENT DATA