Superclass and subclass and abstract method

Hi all,
I am a little bit confused about abstract methods.
I define a superclass without abstract keyword and an abstract method inside the superclass. Then I write a subclass to extend the superclass.
When I compile the source code I get error. It looks like I can't initiate an instance from the supercalss and/or subclass. If I put abstract key word in the superclass definition there is no problem at all. So my question: does abstract method needed to be defined in an abstract superclass only?
Thank for you input.

Abstract methods can only be declared in an abstract class.

Similar Messages

  • Enforce setting private variable in subclass with abstract method

    Hi,
    Is this something that is common usage/practice?:
    public abstract class Base {
        private int importantPrivateVariable = setImportantPrivateVariable();
        protected abstract int setImportantPrivateVariable();
    }I would like to enforce the extender of the class to set a private variable, but as there is no abstract variable in java, I can only use a method for it.
    Thanks,
    lemonboston
    Edit: the variable could be protected as well, I suppose this is not important here, but correct me if I am wrong

    lemonboston wrote:
    Hi,
    Is this something that is common usage/practice?:I don't think that's so common, but that's code easily understandable. However there are several problems with this approach:
    public abstract class Base {
    private int importantPrivateVariable = setImportantPrivateVariable();
    protected abstract int setImportantPrivateVariable();
    }I would like to enforce the extender of the class to set a private variableThat's no what your code implements: your base class forces the subclasses to return an int value, and the Base class uses that value to assign it to the variable.
    Therefore the method should be called get<Something> (e.g. <TT>getInitialValueOfImportantVariable()</TT>+ to have a naming consistent with its signature (it returns a value, whereas a regular setter method should declare a void return type: <TT>protected abstract void setImportantPrivateVariable(int someValue);</TT>).
    Edit: the variable could be protected as well, I suppose this is not important here,Well, yes, this is "important" - at least, there a noticeable difference: the variable being private, the base class is free to handle it as it sees fit (e.g., assign the value at construction time and never modify it afterwards). If the variable was protected, the subclass could modify in ways and at times not known by the base class.
    but correct me if I am wrongThere's a trap in this construct: the method is called in the variable initializer, that is, behind the scenes, approximately during the execution of the Base class constructor, so before the subclass constructor. So, you are calling a method on an object that is not fully initialized (e.g. some of its attributes may still be <TT>null</TT> at this stage). There is a rule that discourages such situations, that goes something like "don't call non-private and non-final methods from a constructor".
    To avoid this trap, two options:
    - require an int argument in the Base class's constructor , as was suggested above
    - don't get and set the value of the important variable in the initializer or constructor code, but from a special method in the base class instead:
    public abstract class Base {
        private int importantPrivateVariable; // default value is zero
    // or alternatively:
    //    private int importantPrivateVariable = ...; // Some default value
        protected abstract int getImportantPrivateVariable();
        public void initializeImportantPrivateVariable() {
            importantPrivateVariable = getImportantPrivateVariable();
    }That construct is a degenerate form of a common design pattern known under the name of Template Method (where a base class method calls generally several subclass methods in a specified order and with a specified chaining, leaving it to the subclass to implement the details of the methods).
    The drawback is that the client code (the one that uses the Base instance) has to know when to call that initialization method, whereas the constructor-based initialization lets the client code free to not care at all.
    Much luck,
    J.

  • Abstract method and class

    I'm a beginner in Java and just learn about abstract method and class.
    However, i am wondering what is the point of using abstract method/class?
    Because when I delete the abstract method and change the class name to public class XXXX( changed from "abstract class XXXX), my program still runs well, nothing goes different.
    Is it because I haven't encountered any situation that abstract method is necessary or ?
    Thanks!

    Yes - you probably haven't encountered a situation where you need an abstract.
    Abstract classes are not designed to do anything on their own. They are designed to provide a template for other classes to extend by inheritance. What you have build sounds like a concrete class - one which you are creating instances of. Abstract classes are not designed to be ever instantiated in their pure form - they act like a partial building block, which you will complete in a class which extends the abstract.
    An example might be a button class, which provides some core functionality (like rollover, rollout etc) but has an empty action method which has to be overwritten by a relevant subclass like 'StartButton'. In general, abstract classes may not be the right answer, and many people would argue that it is better to use an interface, which can be implemented instead of extended, meaning that you can ADD instead of REPLACING.
    Not sure if that helps.. there are whole chapters in books on this kind of thing, so it's hard to explain in a couple of paragraphs. Do some google searches to find out more about how they work.

  • Abstract methods and subclasses

    I have a class, DfContainer that has a method whose return type is of an abstract class, DfObject.
    There are several classes that extend the abstract class. Each of them has methods that are unique to them.
    But in order to be able to execute the methods using the object returned through the method in DfContainer, I need to define each method as abstact in DfObject.
    Now say, I need a method called getNames() in the class DfNames that extends DfObject, and I need a method called getRanks() in DfOrganization that also extends DfObject.
    I would define those two methods as abstract in DfObject. But, I would need to add getRanks() to DfNames, and add getNames() to DfOrganization, even if I don't need them there.
    That's what I'm doing right now. If I don't cast the object returned from the method in DfContainer to a subtype of DfObject, is this the correct approach?
    Thanks,
    Moshe

    Why don't you define an empty method body in the abstract class, that does not have to be overridden in the subclass.
    An abstract class can contain fully implemented methods. You can then override them or not as you choose. You don't have to define your individual methods as abstract.
    Look at the way the various listeners and adapters are done in AWT. You have a listener that's an interface, then a dummy class that provides do-nothing implementations for all methods in the interface, so when you want to override one method you only need to override that specific method, not all the methods in the interface. You should be able to do something similar.

  • Superclass and subclass

    Ok I have now reached the area of using Superclass and subclass in my
    self study of Java, and I am stumped on what is I am sure is a very
    easy concept. Here's the Scenerio. I have three classes Point, Circle
    and InheritanceTest. Point is the Superclass that is being referenced
    from Circle InheritanceTest has the main Method.
    Inside the Point class the book I am using has this note inside the
    constructor.
    public void Point{
    //implicit call to superclass constructor occurs here
    setPoint(0,0);
    My question is this, Is the call to it's self or the object class?
    And do you Know which one it is referring to?
    Thanks in advance

    public void Point{
    //implicit call to superclass constructor occurs here
    setPoint(0,0);
    }When you extend a class, every constructor of the new class must call a constructor of the extended class- this is done by using super() or super(some arguments). Note that if you don't put this in, java will implicitly call super() for you- it basically inserts this call into your new constructor.
    As for the setPoint() method, if your new class has a method of this name and signature (i.e. same type of arguments), it will call your sub-class's method. If the sub-class does not have a method like this defined, it will look for this method in the super-class and call that one. In this way, you are inheriting the methods of the super-class. Unless you specifically override a method (give a method of the same name in type in the sub-class as in the super-class), all public or protected methods of the super-class can be used as if they were methods of your sub-class.
    Check this out:
    public class SuperClass
         private int value = 0;
         public SuperClass()
              super();
              // Calling the default constructor of Object, the superclass of this class
         public SuperClass(int value)
              // Implicitly calling super() since a superclass constructor was not given explicitly
              this.value = value;
         public int getValue()
              return value;
         public void setValue(int value)
         this.value = value;
         public void changeValue()
              setValue(getValue() + 1);
    public class SubClass
         public SubClass()
              super(0);     // Calls the SuperClass(int) constructor
         public SubClass(int value)
              // Implicit call to SuperClass() constructor
              setValue(value);
         public void changeValue()
              // Overrides the SuperClass method of the same name
              setValue(getValue() - 1);
         public void useSuperChangeValue()
              super.changeValue();     // Calls SuperClass.changeValue()
         // If you want to use the super-class methods, even if they have been overridden,
         // use the keyword "super" to reference the superclass

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

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

  • Abstract Method Error and XML Parsing

    I am using wl6sp1. I am parsing an XML file from within the
    servlet using jaxp1.1 and crimson.
    Following is code:
    1- SAXParserFactory spf = SAXParserFactory.newInstance();
    2- sp = spf.newSAXParser();
    3- xr = sp.getXMLReader();
    4- xr.setContentHandler(new ParseXML());
    5- xr.parse( new InputSource("Example3.xml"));
    This program works fine when execute from command line but in servlet on line
    3 it says:
    "Abstract Method Error"
    I have created XML Registry to use Crimson as XML parser rather than default.
    I think somehow wl is still using jaxp1.0 which is built in
    support in wlsp1.
    Whats wrong with the code...or what configuration i am missing???

    I'm assuming you have already put crimson.jar first in the classpath for the java
    command you use to start WebLogic. If so, have you tried putting the servlet in
    a .war file with the crimson.jar in its' WEB-INF/lib directory?
    Regards,
    Mike Wooten
    "anyz" <[email protected]> wrote:
    >
    I am using wl6sp1. I am parsing an XML file from within the
    servlet using jaxp1.1 and crimson.
    Following is code:
    1- SAXParserFactory spf = SAXParserFactory.newInstance();
    2- sp = spf.newSAXParser();
    3- xr = sp.getXMLReader();
    4- xr.setContentHandler(new ParseXML());
    5- xr.parse( new InputSource("Example3.xml"));
    This program works fine when execute from command line but in servlet
    on line
    3 it says:
    "Abstract Method Error"
    I have created XML Registry to use Crimson as XML parser rather than
    default.
    I think somehow wl is still using jaxp1.0 which is built in
    support in wlsp1.
    Whats wrong with the code...or what configuration i am missing???

  • Nested interfaces and abstract methods

    Consider the following design:
    interface ZIF_INTERFACE_A.
      methods METHOD_A.
    endinterface.
    interface ZIF_INTERFACE_B.
      interfaces ZIF_INTERFACE_A.
      methods METHOD_B.
    endinterface.
    class CLASS_A_B definition abstract.
    public section.
      interfaces ZIF_INTERFACE_B
        abstract methods METHOD_B.
      interfaces ZIF_INTERFACE_A
        abstract methods METHOD_A.
      methods METHOD_C.
    endclass.
    class CLASS_A_B implementation.
      method METHOD_C.
      endmethod.
    endclass.
    When trying to implement this design, the syntax check is giving me an error:
    The method "METHOD_A" was declared as not ABSTRACT in a previous INTERFACES statement.
    If I implement the design with Java (either using a public nested interface, or using interface inheritance) there is no problem declaring both the methods METHOD_A and METHOD_B as abstract in the CLASS_A_B class.
    So it seems to me this might be a bug in the ABAP Objects implementation. Or perhaps I am missing something else here? Does anyone have any suggestions?

    Hello,
    Nested interfaces
    When you include an IF in another IF both of them will exist on the same level, there is no concept of hierarchy. So when you add interface ZIF_B in the implementing class ZCL_A_B, the interface ZIF_A is also "included" in the relationship with the class ZCL_A_B implicitly.
    Just try to activate the code below & you'll get the error: "Implementation missing for method zif_interface_a~method_a":
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
    *    INTERFACES zif_interface_a
    *      ABSTRACT METHODS method_a.
        INTERFACES zif_interface_b
          ABSTRACT METHODS: method_b.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
        INTERFACES zif_interface_b
          ABSTRACT METHODS method_b.
        INTERFACES zif_interface_a
          ABSTRACT METHODS method_a.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    So when the compiler is trying to compile your code it encounter implementation of ZIF_INTERFACE_B it finds that the "included interface" method ZIF_INTERFACE_Amethod_a is not abstract. So when you declare ZIF_INTERFACE_Amethod_a as "abstract" in the next line the compiler throws this error.
    So you need to define ZIF_INTERFACE_A~method_a as abstract, before defining ZIF_INTERFACE_B. Like this:
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
        INTERFACES zif_interface_a
          ABSTRACT METHODS method_a.
        INTERFACES zif_interface_b
          ABSTRACT METHODS method_b.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    In this case the compiler treats method_a as abstract while checking ZIF_INTERFACE_B. Hence it doesn't throw any error.
    Hope i'm clear.
    BR,
    Suhas
    PS: Whenever i face any problem while creating local classes, i create a dummy class in the class builder to check

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

  • PLEASE - help With subclass and method

    ok to be honest I am posting here because I am completely lost... I am looking for any help. I have to create a subclass of CD. In this subclass I have to create a method to calculate the value of the inventory of a product with the same name as the method previously created for the product class. The subclass method should also add a 5% restocking fee to the value of the inventory of that product. I will post the code as far as I have come. I do not even know if it compiles it will do anything like I asked it to, my knowledge of java is still growing and I feel I am a little over my head on this.
    Inventory2.java:21: '.class' expected
    ((mName) cd[]).sameName(cd, cd);
    ^
    1 error
    here is the code... any help is greatly appreciated
    import java.text.DecimalFormat;
    public class Inventory2 {
          public CD[] cd;
           public static void main(String[] args) {
             System.out.println("\nCheckPoint: Inventory Part 2");
             Inventory2 inv = new Inventory2();
             CD[] cd = new CD[5];
             DecimalFormat df1 = new DecimalFormat(".00");
                    //Creates new cd
                     cd[0] = new CD("Lily Allen - Alright Still",1,12.50,267);
                     cd[1] = new CD("Daft Punk - Alive 2007",2,12.50,148);
                     cd[2] = new CD("Michael Jackson - Bad",3,9.50,8);
                     cd[3] = new CD("Daft Punk - Alive 2007",2,12.50,148);
                     cd[4] = new CD("Madonna - Immaculate Collection",4,19.50,18);
                     ((mName) cd[]).sameName(cd[1], cd[3]);
                           for (int i=0; i < cd.length; i++)
                                System.out.println(cd);
              System.out.println("Total Inventory Value: $" +df1.format(inv.invValue(cd)));
         System.out.println("\n Sorted Order By Name:" );
         inv.sortCd(cd);     
              for (int i=0; i < cd.length; i++)
                             System.out.println(cd[i]);
    public double invValue(CD[] cd)
                   double inval = 0;
                   for (int i=0; i < cd.length; i++)
         inval += cd[i].itemValue();
              return inval;
    public static void sortCd(CD[] cd)
         int a,b;
         CD[] tempcd = new CD[1];
              for (b = 0; b < cd.length-1; b++)
                   if(cd.getName().compareTo(cd[b + 1].getName()) > 0)
                   tempcd[0] = cd[b];
                   cd[b] = cd[b + 1];
                   cd[b + 1] = tempcd[0];
    and the classesimport java.text.DecimalFormat;
    class CD
    private String aName;//Initializes name
    private int inum;//Initializes number
    private double cost;//Initializes cost
    private int stock;//Initializes stock
    private double value;//Initializes value
    //Constructs CD
    public CD ()
    aName = null;
    inum = 0;
    cost = 0;
    stock = 0;
    public CD (String name, int itemNumber, double price, int inv)
    aName = name;
    inum = itemNumber;
    cost = price;
    stock = inv;
    public String getName()
         return aName;      
    public double itemValue()
         value = stock * cost;//computes item value
         return value;
    //toString when cd is printed it sends
    public String toString()
         DecimalFormat df1 = new DecimalFormat(".00");
         return "CD: No: " + inum + " Copies: " + stock + " Price: $"
              + df1.format(cost) + " Value: $" + df1.format(itemValue()) + " \n " + aName;//returns the cd information
    class mName extends CD {
         double sameName(CD cd1, CD cd2) {
              double b;
              if(cd1.getName().equalsIgnoreCase(cd2.getName()) == true)
                   b = cd1.itemValue();
                   b += cd2.itemValue();
                   b = b * .5;
                   return b;     

    to answer your question corlettk...
    this is a homework assignment, i was required to...
    Modify the Inventory Program by creating a subclass of the CD class that uses one additional unique feature of the product you chose (for the CDs subclass, you could use CD NAME, for example).
    In the subclass, create a method to calculate the value of the inventory of a product with the same name as the method previously created for the product class. The subclass method should also add a 5% restocking fee to the value of
    the inventory of that product.
    ? Modify the output to display this additional feature you have chosen and the restocking fee.
    now as I am said I am completely lost...
    I am not sure where to go from here...
    below is my inventory code and the class' code
    any advise would be greatly appreciated
    I feel like i do not need to add the whole cd only the name..
    import java.text.DecimalFormat;
    public class Inventory2 {
          public CD[] cd;
           public static void main(String[] args) {
             System.out.println("\nCheckPoint: Inventory Part 2");
             Inventory2 inv = new Inventory2();
             CD[] cd = new CD[5];
             DecimalFormat df1 = new DecimalFormat(".00");
                    //Creates new cd
                     cd[0] = new CD("Lily Allen - Alright Still",1,12.50,267);
                     cd[1] = new CD("Daft Punk - Alive 2007",2,12.50,148);
                     cd[2] = new CD("Michael Jackson - Bad",3,9.50,8);
                     cd[3] = new CD("Daft Punk - Alive 2007",18,12.50,148);
                     cd[4] = new CD("Madonna - Immaculate Collection",4,19.50,18);
                     mName.sameName(cd[1], cd[3]);
                           for (int i=0; i < cd.length; i++)
                                System.out.println(cd);
              System.out.println("Total Inventory Value: $" +df1.format(inv.invValue(cd)));
         System.out.println("\n Sorted Order By Name:" );
         inv.sortCd(cd);     
              for (int i=0; i < cd.length; i++)
                             System.out.println(cd[i]);
    public double invValue(CD[] cd)
                   double inval = 0;
                   for (int i=0; i < cd.length; i++)
         inval += cd[i].itemValue();
              return inval;
    public static void sortCd(CD[] cd)
         int a,b;
         CD[] tempcd = new CD[1];
              for (b = 0; b < cd.length-1; b++)
                   if(cd.getName().compareTo(cd[b + 1].getName()) > 0)
                   tempcd[0] = cd[b];
                   cd[b] = cd[b + 1];
                   cd[b + 1] = tempcd[0];
    classimport java.text.DecimalFormat;
    class CD
    private String aName;//Initializes name
    private int inum;//Initializes number
    private double cost;//Initializes cost
    private int stock;//Initializes stock
    private double value;//Initializes value
    private double restock;//Initializes restock
    //Constructs CD
    public CD ()
    aName = null;
    inum = 0;
    cost = 0;
    stock = 0;
    public CD (String name, int itemNumber, double price, int inv)
    aName = name;
    inum = itemNumber;
    cost = price;
    stock = inv;
    public String getName()
         return aName;      
    public void setRestock(double r)
         restock = r;
    public double itemValue()
         value = stock * cost;//computes item value
         return value;
    //toString when cd is printed it sends
    public String toString()
         DecimalFormat df1 = new DecimalFormat(".00");
         return "CD: No: " + inum + " Copies: " + stock + " Price: $"
              + df1.format(cost) + " Value: $" + df1.format(itemValue()) + " \n " + aName;//returns the cd information
    class mName extends CD {
         public static void sameName(CD cd1, CD cd2) {
              double r;
              if(cd1.getName().equalsIgnoreCase(cd2.getName()) == true)
                   r = cd1.itemValue();
                   r += cd2.itemValue();
                   r = r * .5;

  • Abstract method versus static and non-static methods

    For my own curiosity, what is an abstract method as opposed to static or non-static method?
    Thanks

    >
    Following this logic, is this why the "public static
    void main" 0r "Main" method always has to be used
    before can application can be run: because it belongs
    to the class (class file)?
    Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
    RObin

Maybe you are looking for