Abstract Method Overriding Problem

I have an abstract class called "Employee" with an abstract method called "ReturnBasicInfo()" defined.
I have two subclasses, SalariedEmployee and HourlyEmployee, and each has their own version of ReturnBasicInfo(). The compiler is not letting me do this, however, and I have no idea why.
I keep getting this error:
SalariedEmployee.java:6: SalariedEmployee is not abstract and does not override
abstract method returnBasicInfo() in Employee.The abstract method signature is this:
public abstract String returnBasicInfo(Employee e);Any idea why this might be happening? I have another abstract method called toVector() that's overriden in the subclasses and that one works fine, so I'm stumped on this. The only difference between the two is that this method takes arguments and the other doesn't. Is that why it can't be overriden?
Thanks in advance for any help!

"...In the instructor's example code, he actually
overrode toString with this method. I thought I might
be using the real toString(), though, so that's why I
changed the name to returnBasicInfo(). I didn't end up
using toString(), though. Maybe I ought to go back to
calling it toString()..."
Yes, this SHOULD be overridden in toString(). Do go
back to it.
The "real" toString()? Do you mean the default
version in java.lang.Object, the one that just prints
out the object reference when it's called?
Hmm, I guess. I got confused because I'm swapping between String and double values a lot. Taking in an entered number as a String and converting it to a double.
I think I originally confused toString() with String.valueOf().
I wouldn't have getYearlySalary() for SalariedEmployee
and getHourlySalary() for HourlyEmployee. That
defeats the purpose of polymorphism and dynamic
typing. Yes, but I do have one polymorphic method --pay(). Each Employee is paid a different way. The one method we were supposed to be able to call on all Employees is just pay(). There is one version of pay() for HourlyEmployees that uses gethourly_rate() and gethours_worked() to get hourly rate and hours worked. The other version of pay() in SalariedEmployees takes in their yearly salary and number of pay periods worked.
Better to have a getSalary() method in your
Employee interface and let each subclass implement it
the way they want to. SalariedEmployee will return
their yearly salary, HourlyEmployee will return
hourlySalary*hoursWorkedOK, that's one idea.
But darnit, I would still like to know how to get my original design to work. So I should change returnBasicInfo() to toString(), you think?

Similar Messages

  • Method override problems

    I am new to Java programming and this is likely a trivial problem, but I have been unable to find an answer after a few hours in books and on the Web.
    I have created two subclasses of a class, and overridden a public method (the same method) in each of the subclasses. At runtime however, all calls to this method from an instance of the superclass or either subclass results in the same method; i.e. the override in one subclass is overriding the other subclass and the superclass. Why is the scope of this override so large, and how do I fix this?
    Thanks,
    ~Jon Hurst

    I think there must be something wrong in the way the instance is being created. Anyway try running the sample below and you will see that it works the way it is expected to.
    Hope this helps.
    regards
    manalar
    <code>
    public class SuperClass{
    public void display(){
    System.out.println("display in super class");
    import SuperClass;
    public class AnotherClass{
    public AnotherClass(){
              SuperClass sc = new SuperClass();
              sc.display();
              SubClass1 sb1 = new SubClass1();
              sb1.display();
              SubClass2 sb2 = new SubClass2();
    sb2.display();
    public void display(){
    System.out.println("display in AnotherClass");
    private class SubClass1 extends SuperClass{
    public void display(){
    System.out.println("display in SubClass1");
    private class SubClass2 extends SuperClass{
    public void display(){
    System.out.println("display in SubClass2");
    public static void main(String args[]){
    AnotherClass ac = new AnotherClass();
    ac.display();
    </code>

  • 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?
    Cheers

    Sorry, 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

  • Overriding abstract methods with generic argument

    Hi,
    This post is similar to the one posted just before it :
    [http://forum.java.sun.com/thread.jspa?threadID=5281500|http://forum.java.sun.com/thread.jspa?threadID=5281500]
    I am trying to override an abstract method which has a generic argument and a problem occurs. I would like to find out whether what I am trying to do is not legal. The point of interest here is that the overriding class reduces the scope of the abstract class.
    The Abstract class AbstractAdapter defines accessors for a collection containing objects derived from AbstractPort. (<? extends AbstractPort>)
    The overriding class Adapter overrides these accessors but reduces the scope of the collection objects from <? extends AbstractPort> to <Port>. Port
    Here is my abstract class:
    public abstract class AbstractAdapter {
         public abstract Collection<? extends AbstractPort> getPorts();
         public abstract void setPorts(Collection<? extends AbstractPort> ports);
    }And here is the class that overrides it:
    public class Adapter extends AbstractAdapter {
         public Collection<Port> getPorts() {
              return null;
         public void setPorts(Collection<Port> ports) {
    }The Port class is shown here:
    public class Port extends AbstractPort {
    }Edited by: BenDave on Apr 2, 2008 4:39 AM

    It's not really the same.
    I don't have a compiler to hand, so this is off the top of my head. I expect you want something like this:
    public abstract class AbstractAdapter<T extends AbstractPort> {
         public abstract Collection<T> getPorts();
         public abstract void setPorts(Collection<T> ports);
    public class Adapter extends AbstractAdapter<Port> {
         public Collection<Port> getPorts() {
              return null;
         public void setPorts(Collection<Port> ports) {
    }

  • 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 test

    is 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

  • ...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 errors

    According 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;

  • Override Abstract Methods in NetBeans 6.1

    I just upgraded to NetBeans 6.1 and I can't figure out how to automatically override abstract methods... I I know in older versions you could select a menu option and select abstract methods and NetBeans would put them all in for you...

    I'm sorry... I admit that I only looked quickly for a NetABeans forum and didn't find one... What is it under so I know for the future...

  • 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();

  • 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 @Implements

    sabre150 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).

  • Generic Method override compatibility

    I tried to find references to the problem but couldn't. I face it all the time and I thought some else must have had the same problem already.
    Oh well, here it goes.
    With both 3.1M4 and 3.1M5a the following code compiles without any problems.
    public interface MyIface {
        public <T> void foo(T p);
    public class MyClass implements MyIface{
        public <T extends Integer> void foo(T p) {
             //does something
    }However, javac 1.5 gives me:
    MyClass.java:1: MyClass is not abstract and does not override abstract method <T>foo(T) in MyIface
    public class MyClass implements MyIface{
    ^
    1 error
    I found many different variations to this problem, which I am not going to list here as I am trying to be concise. But for the eclipse compiler, <T extends Integer> is the same as <T> in terms of method signature. For the javac compiler these are different thingss.
    Does anyone know if this is a Bug in eclipse or javac, or if this is a known decision, which is taking both tools in different directions?
    Coconha

    Coco, you have to understand how generics work in the compiler to understand this. Basically, erasure means that all the fancy generics stuff you write in your source code gets 'erased' when it gets compiled... So:public interface MyIface {
        public <T> void foo(T p);
    }gets compiled and the resulting .class file, if you decompiled it, would actually look like this:public interface MyIface {
        public void foo(Object p); // NOTICE that "T" gets erased to plain old java.lang.Object
    }See? The same thing happens with MyClass:public class MyClass implements MyIface {
        public <T extends Integer> void foo(T p) {
             //does something
    }after it's compiled, actually looks like this inside the .class file:public class MyClass implements MyIface {
        public void foo(Integer p) { // NOTICE that "T extends Integer" gets erased to plain old Integer!
             //does something
    }Do you see what the problem is now? MyClass has a method called foo(Integer) and MyIface has a method called foo(Object). Obviously now, you see, foo(Integer) shouldn't override foo(Object). The Eclipse compiler should actually complain that you haven't implemented foo(Object) in MyClass. Do you follow?
    Let's look at your second example.public class Base {
      public <S> void foo(S a) {
        System.out.println("Base: " + a);
    public class Sub extends Base {
      public <S extends Integer> void foo(S a) {
        super.foo(a); // should be an error here! super.foo(Integer) doesn't exist!
        System.out.println("Sub: " + a);
    }Let's apply erasure manually and see why there is no error:public class Base {
      public void foo(Object a) {
        System.out.println("Base: " + a);
    public class Sub extends Base {
      public void foo(Integer a) {
        super.foo(a); // calls foo(Object a)! you could also write "this.foo((Object)a)"
        System.out.println("Sub: " + a);
    }Sub actually has two methods - foo(Integer a) which it defines explicitly - and foo(Object a) which it inherits from Base.

  • Static abstract methods - how can I avoid them?

    Hi everybody,
    just found out that java doesn't allow static abstract methods nor static methods in interfaces. Although I understand the reasons, I can't think of how to change my design to gain the required behavior without the need of static abstract methods.
    Here's what I want to do and how my thoughts lead to static abstract methods:
    ClassA provides access to native code (c-dll, using jna). The path to the dll can be set programmatically. Here's a draft of the class:
    public ClassA {
       private static String path;
       public static void setRealtivePath(String path) {
          //check if path exists and is not null -> get absolute path
          setPath(path);
       public static void setPath(String absolutePath) {
          this.path = path;
      //code to provide access to native lib
    }There is some more classes which provide access to different dlls (therefore the code for accessing the dlls differs from ClassA). Although this works, the setRelativePath method has to be implemented in each class. I thought it would be nice to put this method into a abstract super class that looks like this:
    public abstract class superClass {
       public static void setRelativePath(String path) {
          //check if path exists and is not null -> get absolute path
          setPath(path);
       //force inherting class to implement a static method
       public static abstract void setPath(String absolutePath);
    }thus simplifying ClassA and it's look-a-likes:
    public ClassA {
       private static String path;
       @Override
       public static void setPath(String absolutePath) {
          this.path = path;
      //code to provide access to native lib
    }Since static abstract methods (and overriding static methods) is not allowed, this doesn't work.
    I hope someone can catch my idea ;). Any suggestions how to do this in a nice clean way?
    Thanks in advance,
    Martin
    Edited by: morty2 on Jul 22, 2009 2:57 AM

    First of all, thanks a lot for your answer.
    YoungWinston wrote:
    Actually, you can "override" static methods (in that you can write the same method for both a subclass and a superclass, providing the superclass method isn't final); it's just that it doesn't work polymorphically. The "overriding" method masks the overridden one and the determination of what gets called is entirely down to the declared type.Yes, I know that. There's one problem: Your suggestion means that I simply have to drop the abstract modifier in the super classes setPath method. However, since the super class calls the setPath method (and not the inherting classes!) it will always be the super classes' method being called.
    YoungWinston wrote:
    Why are you so concerned with making everything static? Seems to me that the simplest solution would be to make all the contents instance-based.I want ClassA and it's look-a-likes to be set up properly at application start up, be accessible quite anytime and easily, they don't do anything themselves except for setting the path and calling into the native library which does the math. (Compareable to how you call e.g. Math.cos()). Therefore I don't think that an instance-based solution would be a better approach.
    YoungWinston wrote:
    Furthermore, you could make the class immutable; which might be a good thing - I'm not sure I'd want someone being able to change the pathname after I've >set up a class like this.Thanks for that!
    PS: As mentioned in my first post, I do have a working solution. However, I'm really corious about finding a nicer and cleaner way to do it!
    Martin

  • Overridden methods  run like an abstract method

    public class Mammal
    public int length;
    public Mammal(int b)
    this.length=b;
    public void speciesName()
    System.out.println("I am a mammal");
    public class Cat extends Mammal
    public Cat (int b)
    super(b);
    public void speciesName()
    System.out.println("I am a Cat");
    public class Goat extends Mammal
    public Goat(int b)
    super(b);
    public void speciesName()
    System.out.println("I am a Goat");
    public class Test
    public static void main(String[] args)
    Cat k=new Cat(50);
    Goat g=new Goat(60);
    Vector<Mammal> v=new Vector<Mammal>();
    v.add(k);
    v.add(g);
    Mammal m; //reference
    m=v.elementAt(0);
    m.speciesName();
    m=v.elementAt(1);
    m.speciesName();
    hello all,
    my problem about above code is:
    on the console : I am a Cat
    I am a Goat
    but i did not understand why the result is so this.
    i thought that the screen output must be : I am a Mammal
    I am a Mammal
    i supposed that Mammal class's speciesName() method must run.
    if speciesName() was abstract method, i could understand the result.
    but in this situation, i didn't understand how the output is this.
    thanks...

    khanD wrote:
    i thought that the screen output must be : I am a Mammal
    I am a Mammal
    i supposed that Mammal class's speciesName() method must run.
    if speciesName() was abstract method, i could understand the result.
    but in this situation, i didn't understand how the output is this.Now you know that it doesn't matter whether speciesName in Mammal is abstract or not. Overriding works the same regardless.
    But there are other differences. For example right now Mammal is concrete so you could create a Mammal object if you wanted. If you made speciesName abstract that would no longer be possible. Right now you also don't have to override speciesName in the subclasses. If speciesName were abstract you would have to do that.

  • Force method overriding

    Hi, my problem is the following: (basic sketch)
    class A {
         public void y() { ... x(1, 5); ... }
         protected void x(int i, int j) { ... }
    class B extends A {
         protected void x(int i, int j) { ... }
    The meaning of which is that B is supposed to change part of y()'s behavior.
    Now when in a project classes are modified all around, it may happen that someone changes the signature of A.x(), say to x(int i, int j, int k)
    This immediately causes that calling B.y() produces no different behavior than calling A.y(), which is not intended.
    So is there a way to force that B.x() must override a method in the base class? I would like to have it such that if A.x()'s signature changes and B.x()'s not, then a compile-time error occurs. (It makes sense if x() is some function with distinctive charasteristics, no overloaded forms, etc.)
    Maybe it can be reached somehow with abstract methods?
    Thanks,
    Agoston

    Something like this is what I've finally come up with:
    Please note that I wasn't allowed to change the fact that B extends A for other reasons in the real application.
    class A {
         protected interface I {
              void x(int i, int j);
         private static class AX implements I {
              public void x(int i, int j) { ... }
         private I getI() { return new AX(); }
         public void y() {
              I i = getI();
              i.x(1, 5);
    class B extends A {
         private static class BX implements I {
              public void x(int i, int j) { ... }
         private I getI() { return new BX(); }
    Requires a little additional work, but it's worth it so you don't have to check A if x()'s signature is still the same and B still does what you want, because whoever changes AX.x()'s signature, has to change I as well, and gets a compilation error if BX.x() isn't modified accordingly.

Maybe you are looking for