Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Abstract Methods [duplicate]

I am slightly confused with the keyword abstract here. My compiler is telling me that I am not allowed to have a body for a method that's abstract. However my assignment says:

The abstract method orderDescription() returns a String giving details about a particular order.

abstract String orderDescription()
{
    return null;
}

However my code returns an error, as I mentioned above. So my question is what should I do for this problem?

Up to now I've just removed the keyword abstract and it works fine.

like image 461
Matthew Brzezinski Avatar asked Nov 13 '12 19:11

Matthew Brzezinski


3 Answers

abstract String orderDescription()
{
    return null;
}

should be

abstract String orderDescription();

As error says, your abstract method declaration shouldn't contain any body.

Above syntax mandates the implementation (which ever class extends the abstract class and provides implementation) to return a String.

You can't instantiate abstract class, so some class need to extend abstract class and provide implementation for this abstract method.

Example:

class MyabsClass 
{
  abstract String orderDescription();
}

class MyImplementation extends MyabsClass
{
   public String orderDescription()
    {
    return "This is description";
    }
}



 class MyClient
   {
     public static void main(String[] args)
      {
         MyImplementation imple = new MyImplementation();
         imple.orderDescription();
      }
   } 
like image 156
kosa Avatar answered Oct 25 '22 17:10

kosa


When you define an abstract method, you are telling the compiler that any subclasses must provide an implementation (or also declare themselves abstract).

You implement the abstract method in a subclass.

Remember, you cannot create instances of abstract classes themselves. The entire point of an abstract method is to tell the compiler that you want subclasses to provide the functionality.

like image 40
hvgotcodes Avatar answered Oct 25 '22 16:10

hvgotcodes


Essentially, an abstract function shouldn't contain any details, it is a placeholder function for inherited functions. As Nambari stated, you should only include the definition.

This is used for when you want a family of classes to all contain a common function, which you wish each child class to define.

like image 6
PearsonArtPhoto Avatar answered Oct 25 '22 16:10

PearsonArtPhoto