Concept of Abstraction and Polymorphism

Hi friends,
I'm just new to Java.I studied a little bit of C, I'm currently studing VB and Java.
There are one or two concepts in Java that are very hard to grasp for me.
The first is abstraction and the second is polymorphism.
Can anybody outline to me in simple words(use simple example if needed)what those 2 concepts are all about?
Thanks a lot
Marco

In your example, you could make Vehicle an abstract
class. You can't simply have a vehicle, but you can
have a car which IS a vehicle. In your abstract class
Vehicle, you might define an abstract method public
int getSeats() (you want it to be abstract because it
changes from one type of vehicle to the next). So the
class Car extends Vehicle, overrides the method
getSeats() and returns 5. The class Ute extends
Vehicle, overrides the method getSeats() and returns 2
(you might make a SuperCabUte that extends Ute and
returns 5, or whatever).Radish is right,
Think of it as modelling of real life. You would generalise the description of your car as a Vehicle (abstraction, which can be implemented as an interface in Java) where in fact you own a car
Similarly you can have an inteface called RealEstate where in fact you own a TwoStoreyHouse ( a class that implements the RealEstate interface)
the interface can describe the general 'characterstics' of real estate properties ie land size, council rates etc.
HTH...hey....

Similar Messages

  • Abstraction and Encapsulation i.e basic oops concepts gist and their unders

    I have gone to many sites and everywhere got some difference in defintion of abstraction and encapsulation.
    Below i tried to summarize the findings of both and have some questions which are inline with understanding.
    Encapsulation:-
    Hiding internal state and requiring all interaction to be performed through an object's methods is known
    as data encapsulation — a fundamental principle of object-oriented programming.
    Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
    Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
    methods. Is it not the violation of encapsulation? What advantage it provides exposing the internal state thru methods
    (like getter and setter) but not declaring stae with public modifier.?
    Question2:- If class does not have any state variable and has some just simple methods printing hello world.
    Can we still say it is encapsulation?
    Abstraction:-Abstraction in Java allows the user to hide non-essential details relevant to user.
    Question1:- so we can say Encapsulation is also a feature of abstraction because in ecapsulation also we hide data(state) of object. Right?
    Question2:-Say a class has 10 methods . Out of these 10 , only two are exposed for outside world with public modifier.Can we say this is the example of abstraction?
    Question3:- Can we say interface/abstract class are the baset examples of abstraction as they just expose the masic details i.e signature of method to outside world?

    JavaFunda wrote:
    Hi jverd whats your take on original post?Question1:- Agreed that we are hiding the instance variable details but again we do expose them with getter and setter
    methods. Is it not the violation of encapsulation? What advantage it provides exposing the internal state thru methods
    (like getter and setter) but not declaring stae with public modifier.?
    >
    I don't think you can say whether an individual get/set "violates encapsulation" without more context. If you're just blindly providing direct get/set for every member variable, then it's likely you don't understand encapsulation. There's still some encapsulation there, however, because the caller can't directly see or modify the state.
    Sure, a programmer familiar with coding conventions and possessing some common sense could infer that those get/set methods correspond directly to member variables of the same names, but so what? He still has to go through the methods to see or modify the state, and there could be other stuff going on there. The fact that going through the method makes it a black box to him is why I say there's some level of encapsulation. There's a continuum of how "direct" the access to the internal state is, and I don't think there's a clear delineation between "encapsulated" and "not encapsulated."
    For example:
    As direct as can be: setX() is simply this.x = x and getX() is simply return x.
    Somewhat less direct: getFullName() returns firstname + " " + lastName. There's no member variable called "fullName", and the result is composed by operating on multiple pieces of the object's state.
    Still less direct: ArrayList's toString() is "[", followed by the results of each of its elements' toString() methods, separated by commas, followed by "]"
    Very indirect: Map.put(). We know that it modifies the state of the Map by adding the key/value pair we specify, and we can infer some things about how it's implemented based on the type of Map. But that abstraction is so far separated from the specific state that represents it, that we would probably say that there's a high level of encapsulation there.
    And of course there are other scenarios in between these, and further toward the "encapsulated" end of the spectrum than the Map example. Where do you draw the line between "not encapsulated" and "encapsulated"?
    I think a reasonable criterion to use is whether the exposed stated has been exposed because it's a natural part of the behavior of the class.
    For instance, Colleciton.size(). It makes sense that as part of a Colleciton's behavior, you'd want it to be able to tell you how many items it holds. In an ArrayList, you would probably have a size variable that gets updated each time an element is added or removed. However, in a ConcurrentSkipListSet, there is no size variable. You have to traverse the Set and count the elements. So is size encapsulated here? Is it in one but not the other? Why? I would say it is in both cases, because part of the natural behavior of a Collection is to tell us its size, so the fact that in some collections that can be done simply be returning the value of a member variable doesn't "violate" encapsulation.
    But, after having said all that, my real answer is: I don't care. The answer to "Do get/set violate encapsulation?" doesn't matter to me in the least in how I write my code.
    >
    Question2:- If class does not have any state variable and has some just simple methods printing hello world.
    Can we still say it is encapsulation?
    >
    I would say no, since there's no state to be encapsulated. However, I supposed one could say that the behavior is encapsulated. It could be implemented any number of different ways, some of which would involve state and some wouldn't, and all we'd see is the public interface and the behavior it provides. I don't know that anybody actual does view it that way though.
    And, again, this sort of nitpickery is not actually relevant to anything, IMHO.
    >
    Question1:- so we can say Encapsulation is also a feature of abstraction because in ecapsulation also we hide data(state) of object. Right?
    >
    More silly semantics. I wouldn't say that encapsulation is a "feature" of abstraction. I think the two often work together, and there's some overlap in their definitions, or at least in how they're realized in code. (Which can be seen in my long-winded answer to the first quetsion.)
    >
    Question2:-Say a class has 10 methods . Out of these 10 , only two are exposed for outside world with public modifier.Can we say this is the example of abstraction?
    >
    Don't know, don't care.
    >
    Question3:- Can we say interface/abstract class are the baset examples of abstraction as they just expose the masic details i.e signature of method to outside world?
    >
    No idea what you're saying here, but I expect my answer will again be: "don't know, don't care".
    Edited by: jverd on Aug 3, 2011 10:22 AM
    Edited by: jverd on Aug 3, 2011 10:22 AM

  • What is difference between abstraction and encapsulation ?

    Hi,
    I am trying to figure out the difference between abstraction and encapsulation but confused.
    Both are used for data hiding then what is the exact difference ?
    Thanks.

    Tushar-Patel wrote:
    I am trying to figure out the difference between abstraction and encapsulation but confused.
    Both are used for data hiding then what is the exact difference ?This is the picture I have:
    When you encapsulate something you get an inside and an outside. The outside is the abstraction. It describes how the encapsulated entity behaves viewed from the outside. This is also called the type. Hidden inside is the implementation. It holds detail information about how the type's behaviour is accomplished.
    It's a very simplified picture but I think it's quite accurate and it works for me.

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

  • Concept of hide and clear

    Problem understanding hide and clear concept...
    for example, in the code below, it works fine with the write statement and have no problem with the output value when use the back button.
    however, when i use it to call a transaction (eg. mm03) and pass the value over, it seems to be a value behind (eg. when i click on row1, it gives a previously stored value. Press back button and when i click on row2, it gives me value of 1. Press back button and when i click on row5, it gives me value of 2. so the clear doesn't seem to "clear")
    what could be the problem? hope to understand this concept of hide and clear better (eg. when to clear?)...
    Cheers,
    Charles
    ABAP newbie
    DATA number(18) TYPE c.
    START-OF-SELECTION.
      CLEAR number.
      DO 9 TIMES.
        WRITE: / 'Row', (2) sy-index.
        number = sy-index.
        HIDE number.
      ENDDO.
    AT PF8.
      CHECK NOT number IS INITIAL.
      CALL TRANSACTION 'MM03'.
      SET PARAMETER ID 'MAT' FIELD number.
      CLEAR number.
    *  WRITE: / 'Cursor was in row', (2) NUMBER.

    hi,
    chk this.
    HIDE
    Basic form
    HIDE f.
    In an ABAP Objects context, a more severe syntax check is performed that in other ABAP areas.
    See Constants not allowed in HIDE area.
    Effect
    Retains the contents of f related to the current output line.
    When the user selects the line from the list f is automatically filled with the retained value.
    The selection can occur in:
    AT LINE-SELECTION
    AT PFx
    AT USER-COMMAND
    READ LINE
    The contents of the field do not have to have been displayed using WRITE in order for you to retain them.
    The HIDE statement does not support deep structures (structures that contain internal tables).
    Useful system fields for interactive reporting are listed in the System Fields for Lists documentation.
    Note
    Lines or components of lines of an internal table that you address using a field symbol (see ASSIGNING addition to the READ and LOOP statements), cannot be retained using HIDE. You can store them using a global variable instead.
    Note
    Runtime errors:
    HIDE_FIELD_TOO_LARGE: The field is too long for HIDE.
    HIDE_ON_EMPTY_PAGE: HIDE not possible on an empty page.
    HIDE_NO_LOCAL: HIDE not possible for a local field.
    HIDE_ILLEGAL_ITAB_SYMBOL: HIDE not possible for a table line or component of a table line.
    and also a sample program.
    report zxy_0003.
    data: begin of itab occurs 0,
    field type c,
    end of itab.
    itab-field = 'A'. append itab.
    itab-field = 'B'. append itab.
    itab-field = 'C'. append itab.
    itab-field = 'D'. append itab.
    itab-field = 'E'. append itab.
    loop at itab.
    format hotspot on.
    write:/ itab-field.
    hide itab-field.
    format hotspot off.
    endloop.
    at line-selection.
    write:/ 'You clicked', itab-field.
    It kind of "remembers" what is written, so that when you click on it, it knows what the value is.
    Regards,
    anver

  • Concept of util and helper classes

    whats the concept behind helper and util classes, how to divide code according to both perspective would any one state clear separation line b/w them.

    They're just names, dude

  • Concept of sparse and densely populated cubes

    Hi BW Experts,
    Does SAP have a concept of sparse and densely populated cubes?
    Basically, are there any performance differences in a cube with little transactional data loaded and a cube with a lot of transactional data loaded?
    Thanks,
    Rohan

    Hi dear,
    about compression, refer to the following link:
    http://help.sap.com/saphelp_bw33/helpdata/en/ca/aa6437e7a4080ee10000009b38f842/frameset.htm
    When you compress an infocube you bring data from different requests (ID)together into one single request (even if in this case you cannot do anymore any selective deletion...)
    About density and sparsity, look at Wikipedia (!!!):
    http://en.wikipedia.org/wiki/Essbase
    Hope it helps!
    Bye,
    Roberto

  • Illegal combination of modifiers: abstract and synchronized

    Hello all:
    I have an error from my java compiler and need some help to know the underlying reason
    why this statement is wrong.
    the following statement is defined in an abstract class.
    public abstract synchronized boolean isLeaf();when I try to compile it, i got the following error.
    illegal combination of modifiers: abstract and synchronized
    so i know this statement is not valid.
    does anyone tell me why?
    thank you
    -Daneil

    synchronization of a method is not inherited. the synchronized keyword, when applied to a method realy is a short-cut to put this about the method body:
    //instance method:
    synchronized(this)
    //static method
    synchronized(Blah.class)
    }It only applies to the currently declared method. There is no way to require that an implementation of tyour method is synchronized.

  • Diffence between OVERLOADING and POLYMORPHISM

    hi all
    i need the differneces between
    overloading and polymorphism (atleast 3 differences :)))
    regards,
    venkat.

    can u send me any list of core java questions if u have. http://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal - in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

  • Abstract Class and polymorphism - class diagram

    Hi,
    ]Im trying to draw a class diagram for my overall system but im not too sure how to deal with classes derived from abstract classes. I'll explain my problem using the classic shape inheritance senario...
    myClass has a member of type Shape, but when the program is running shape gets instantiated to a circle, square or triangle for example -
    Shape s = new circle();
    since they are shapes. But at no stage is the class Shape instantiated.
    I then call things like s.Area();
    On my class diagram should there be any lines going from myClass directly to circle or triangle, or should a line just be joining myClass to Shape class?
    BTW - is s.Area() polymorphism?
    Thanks,
    Conor.

    Sorry, my drawing did not display very well.
    If you have MyClass, and it has a class variable of type Shape, and the class is responsible for creating MyClass, use Composition on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it has a class variable of type Shape, and the class is created elsewhere, use Aggregation on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it is used in method signatures, but it is not a class variable, use Depedency on your UML diagram to link Shape and MyClass. The arrow will point to Shape.
    Shape and instances of Circle, Triangle, Square, etc. will be linked using a Generalization on your UML diagram. The arrow will always point to Shape.
    Anything that is abstract (class, method, variable, etc.) should be italicized. Concrete items (same list) should be formatted normally.
    BTW, the distinction between Composition, Aggregation and Dependency will vary from project to project or class to class. It's a gray area. Just be consistent or follow whatever guidelines have been established.
    - Saish

  • Method signature (Chapter : Abstract class and Polymorphism)

    Hi all,
    I found some quaint thing about signature method. It's said: "A child class may define additional methods with signatures different from the parent's method." but
    "It is an error if a child defines a method with the same signature as a parent method, but with a different return type."
    The thing is: return type is not belong to method's signature !!!
    Can someone explain this point?
    Thanks and have a nice day ( 11:00 am in Germany)
    H.A

    "It is an error if a child defines a method with the
    same signature as a parent method, but with a
    different return type."
    The thing is: return type is not belong to method's
    signature !!!
    Can someone explain this point?Yes.
    Even though return type isn't part of the "signature" (as the JLS defines "signature"), the JLS requires that child methods with the same signature as parent classes have the same return type.
    Think about it for a minute: Return type isn't part of the signature, but it is part of the contract. If Parent has public Whatsit foo() then it's promising that every instance of Parent, AND every instance of any Child that is a subclass of Parent (since a Child also IS A Parent), will have that method, and callers of that method will receive a Whatsit as a return value.
    If I try to override it in Child with public Doobley foo() then a call might try to do this: Parent parent = factory.createParent(); // happens to return a Child, which is allowed, because a Child is a Parent
    Whatsit w = parent.foo(); // OH NO! We got bad a Doobley instead of a Watsit! See the problem?
    Now, it turns out that 1.5 adds covariant return types, which allows a child method to return a subtype of what the parent returns. So the above would work IFF Doobley is a subclass or subinterface of Whatsis, or is a class that implements Whatsis. This works because the child is still keeping the parent's contract. He's just actually promising a bit more than what the parent promises.

Maybe you are looking for

  • Open_Form Error Please help

    Hi All, I configured the Smart Form at the Respective Transaction on entry_new. I am getting Open_Form Error. what should I change, do I need to change any parameters????. Thanks in Advance. Regards, Praveen

  • 0FI_AR_4 Extractor Enhancement without user exit code Question

    Hi I have a requirement to enhance 0FI_AR_4 Extractor with below Fields from BSID: Field     DataElement PRCTR       PRCTR VPOS2       NUM06 VBUND       RASSC As per SAP Note: 410799, I am assuming I don't need to write any ABAP code to populate thes

  • How to debug a Package / function in PL SQL developer ??

    How can we debug a Package / function in PL SQL developer ?? i want to debug a code line by line

  • AddPartialTarget doesn't refresh the region

    Hi, i have a region where a taskflow is consumed. After doing some update through the ui page , the values in main page remains but the values in the region disappears. when i press F5 the data in region comes in page. However through code when i do

  • Time Capsule, Looking for backup

    Since the recent software update my timecapsule isnt backing up anymore, my drive seems to mount and appear on the desktop and i can see the drive but all i get is looking for backup, in the time machine prefrences i have tried re selceting disks and