Overriding Constructor Method
Hello,
I want to write a class that heritances behaviour and porpoerties of the superclass. Is it possible to execute the methods of the superclass in the subclass? Instead I could write a method in the superclass and call it inside constructor of the subclass, but that seems like a trick to me.
Is it possible to execute the methods of the superclass in the
subclass? Instead I could write a method in the superclass and call it
inside constructor of the subclass, but that seems like a trick to me.
If you are talking about calling super class constructor in subclass, you can do that:
public function SubClassConstructor(){
super();
If you need to call function of superclass, well, you have to write it in superclass, right? Just make it either public or protected.
Similar Messages
-
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. -
How to override a method in an inner class of the super class
I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
The code below is representative of my situation.
public class ClassA
ValueChecks vc = null;
/** Creates a new instance of Main */
public ClassA()
System.out.println("ClassA Constructor");
vc = new ValueChecks();
vc.checkMaximum();
// I want this to call the overridden method, but it does not, it seems to call
// the method in this class. probably because vc belongs to this class
this.vc.checkMinimum();
this.myMethod();
protected void myMethod()
System.out.println("myMethod(SUPER)");
protected class ValueChecks
protected boolean checkMinimum()
System.out.println("ValueChecks.checkMinimum (SUPER)");
return true;
protected boolean checkMaximum()
return false;
}I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
public class ClassASub extends ClassA
public ClassAInner cias;
/** Creates a new instance of Main */
public ClassASub()
System.out.println("ClassASub Constructor");
protected void myMethod()
System.out.println("myMethod(SUB)");
protected class ValueChecks extends ClassA.ValueChecks
protected boolean checkMinimum()
System.out.println("ValueChecks.checkMinimum (SUB)");
return true;
}The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
// I want this to call the overridden method, but it does not, it seems to > call
// the method in this class. probably because vc belongs to this class
this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original. -
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; -
In Java it is simple to extend a class and override a method - the whole idea of polymorphism. In abap, I'm attempting to do the same, but don't know quite how. I've created as a demo a zclass and made a sap standard class its superclass in properties. How do I override a protected method from here?
Marcin says:
Unfortunatelly overriding is not possible in ABAP, only redefinition is allowed. The method singature must stay the same in all subsequent classes.
I guess,
Overriding - Redefinition of the implementation of inherited method. This is possible by addition REDEFINITION to the method.
Overloading - Changing the method parameters of inherited method
Regards,
Naimesh Patel -
My constructor method is bogged!
Hi There,
I've got some problems with constructor methods in my program, of course the constructors look fine to me, but then faulty code usually looks good to any programmer after enough hours! Here is some of my code, firstly the following snippet shows the objects being instantiated.
public static ButtonData BtData1;
public static ButtonData BtData2;
public static ButtonData BtData3;
public static ButtonData BtData4;
public static ButtonData BtData5;
public static void main(String[] args)
try{
inStream = new FileInputStream("ObjStore");
objStreamIn = new ObjectInputStream(inStream);
if(objStreamIn.available() == 0)
objStreamIn.close();
inStream.close();
BtData1 = new ButtonData("Link1",null);
BtData2 = new ButtonData("Link2",null);
BtData3 = new ButtonData("Link3",null);
BtData4 = new ButtonData("Link4","Zero");
BtData5 = new ButtonData("Link5","Zero");
else
}catch(IOException e){}
GUI xyz = new GUI();
}Alot of the above code is related to serialization -- mainly checking to see whether or not objects already exist on file, and if they do not, instantiating them. Notice that the above constructors have different parameters or arguments (I can't remember which word describes it best!) -- it doesn't seem to matter whether I use two strings such as ("Link4","Zero") or ("Link1",null) -- both create errors. The class that is instantiated looks like this:
import java.io.*;
public class ButtonData implements Serializable
String Name;
String Path;
ButtonData(String Name,String Path)
this.Name = Name;
this.Path = Path;
protected String getName()
return Name;
protected String getPath()
return Path;
protected void setName()
Name = Begin.LinkName.getText();
protected void setPath()
Path = Begin.ExecT.getText();
}As far as I can tell the constructor above follows all the relevant syntax rules, as does the first snippet of code that I provided -- where the objects are instantiated. I will probably feel like a real meat head if I have done something dump and obvious, however I have double checked the code and it looks fine to me. When trying to compile the code I get the following error messages (using JBuilder7) -- these error messages highlight the relevant sections of the first code snippet I provided:
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 61, column 23
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 62, column 23
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 63, column 23
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 64, column 23
"Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 65, column 23If anybody can shed some light on what is going on here it will be greatly appreciated.
ThanksThanks everybody for your kind constributions, unfortunately I have tried all suggestion provided and have come up with naught. As both classes are in the same package, the question of scope is resolved, and making the ButtonData objects constructor public has no effect on the error messages displayed. I have also modified the ButtonData class so that accessor and mutator methods are public and variables are private, unfortunately this also has had no effect on the immediate error messages. If anybody has further suggestions they will be greatly appreciated. I thought perhaps that the issue with the constructor may be related to the implementation of the serializalbe interface ----->
beyond that idea I am seriously stuck! -
The equals method accepts Object as the parameter. When overriding this method we need to downcast the parameter object to the specific. The downcast is not the good idea as it is not the OO. So can anyone please tell me how can we override the equals method without downcasting the parameter object. Thank you.
For comparing the objects by value overriding the equals method what I did is like this
public boolean equals(Object o){
if( o instanceof Book){
Book b = (Book)o;
if(this.id == b.id)
return true;
return false;
}But in the above code I have to downcast the object o to the class Book. This downcasting is not a good as it is not Object-Oriented. So what I want to do is avoid the downcasting. So any idea how to do it? -
How to override ExecuteWithParms method?
How I can override ExecuteWithParms method?
as when click on execute button there are many parameters should return result from another table
as select query from different table, can i do this? and how??thanks Timo. this is more detail
I have two table Fundemental and Emails and I have many search parameters
so I need to make custom adf search when click on execute search, get result from all search parameters
so i need to override executeWithParms to change return value when search in pEmail parameter
to return "ID_NO IN (SELECT PERSON_CODE FROM EMAILS WHERE EMAIL LIKE '%" + getpEmail() + "%')"; -
How to override toString() method ?
class Test
String x[];
int c;
Test(int size)
x=new String[size];
c=-1;
public void addString(String str)
x=new String
x[++c]=str;
public void String toString()
// i want to override toString method to view the strings existing in the x[]...
// how do i view the strings ?
// probabily i should NOT use println() here (..as it is inside tostring() method ..right? )
// so i should RETURN x[] as an array...but the toString() method return type is String not the String array!.
// so i am in trouble.
so in a simple way my question is how do i override toString() method to view the Strings stored in the array ?
i am avoiding println() bcoz of bad design.
}AS you said, the toString method returns a String - this String is supposed to be a representation of the current instance of your class's state. In your case, your class's state is a String array, so you just pick a format for that and make a String that fits that format. Maybe you want it to spit out something like:
Test[1] = "some string"
Test[2] = "some other String"If so, code something like:public String toString() {
StringBuffer returnValue = new StringBuffer();
for (int i = 0; i < x.length; i++) {
returnValue.append("Test[" + i + "] = \"" + x[i] + "\"";
return returnValue.toString();
} If you don't mind the formatting of the toString method that Lists get, you could just do something like:public String toString() {
return java.util.Arrays.asList(this).toString();
} and call it good. That will print out something like:
[Some String, another String, null]Depending on what's in your array.
Good Luck
Lee -
Declaring constructor method public or private. What's the point?
My book declares the constructor method public. I tried declaring it private, and without any modifier out of curiousity. It runs exactly the same. What's the point of doing so?
public class test
public static void main( String[] args )
test fun = new test();
test fun2 = new test(2);
System.out.println( fun );
// System.out.println( test.toString() );
public String toString()
return "This is the toString";
test()
System.out.println( "This is the constructor method" );
test( int x )
System.out.println( "This is the constructor method: " +x );
}yougene wrote:
I'm new to OOP so maybe I'm not completely grasping the terminology. But this program works just fine with my class.
public class test2
public static void main( String[] args )
test foo = new test();
}It gives me the following output
----jGRASP exec: java test2
This is the constructor method
----jGRASP: operation complete.The constructor method is executing from an outside class. I tried this with and without the private modifier on the constructor. Same result.Try compiling this.
public class C1 {
private C1() {
System.out.println("C1 c'tor");
public class C2 {
public void foo() {
C1 c1 = new C1();
} -
How to override truncateToFit method for SuperTabNavigator
Hi All,
How to override truncateToFit method for SuperTabNavigator.
we have editableLabel method for changing the tab name.
it is dispalying the ... elipse when entered characters grater than the tab width. it is ok.
but if the entered characters less than the tab width it is also appending the ... elipse.
i dont want that . how to remove those. i dont want completely truncateToFit option.
how to override .
Can any help me regarding this?
Thanks in Advance
Raghu.Give me a sample codeNo. Read the links provided by Yannix, try it out for yourself, and if you still have a question, post the code you tried.
db -
Overriding Interface methods via JNI
Hello,
How we can override Interface methods via JNI?
For example:
At HelloWorldSwing example:
http://download.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java
I've written anonymous Interface as:
import javax.swing.*;
public class HelloWorldSwing1 {
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
static Runnable runnableObject = new Runnable() {
public void run() {
createAndShowGUI();
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(runnableObject);
}via JNI functions(http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html) we cannot override Runnable Interface's run method? Can we?
Only:
RunnableClass's value isn't null with given example at below. FindClass finds the Runnable Interface.
jclass RunnableClass;
RunnableClass = (*env)->FindClass(env,"java/lang/Runnable");
if( RunnableClass == NULL ) {
printf("can't find class Runnable\n");
exit (-1);
}But How can we override Runnable class's run method?
Thanks in AdvanceThe only way you can override a method in Java is by defining a class that does so, either statically or as an anonymous inner class. You can't do either of those things in JNI. Ergo you cannot do what you are asking about.
Maybe you are looking for
-
Invalid Cursor Position Error on Windows XP using CachedRowSet
Hello, I don't know if this question lies here, but I thought it would be the well suited place so please pardon me if it isn't. I am trying to access multiple pages from my database on my XP machine but I am getting an "invalid cursor position" erro
-
Find corresponding BPM to message in SXMB
Hello everybody, we made a mass test: 500 IDOCs where send through BPM to call a JDBC insert. Now there is just one insert with an error and I want to find the corresponding BPM to find out, which IDOC caused the error. Where is the link from SXMB_M
-
toda vez em que eu abro uma pagina aparece um popup com a mensagem para baixar adobe flash player 11.5.50.216, tanto aceitar ou não transfere um arquivo .zip
-
Settings - phone - my number doesn't show up
My phone number doesn't show up in phone settings? and on other iPhones it works. Is there something to turn it on?
-
can SDN provide me guidance to make a file to IDOC scenario, specially the settings at the XI and at the receiver SAP R/3 side..... i m new to XI so, setting details are important,