Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I got several explanations but so far I'm not able to understand that what are the abstract classes and methods in Java. Some said it has to do something with the security of the program, other said it isn't anything like that. Even from the Dietel & Dietel's book I don't get it's purpose. When, where and why do we use it?

share|improve this question
7  
One thing's for sure: it has absolutely nothing to do with security. –  Michael Borgwardt Dec 11 '12 at 16:28
1  
My OOP lab teacher said it has to deal with security, while other teacher disagreed. –  Umer Hassan Dec 11 '12 at 16:31
    
@UmerHassan: The lab teacher needs to explain themselves better, because without an explanation of what abstract classes have to do with making code more secure, I'd say they're simply wrong (and agree with your other teacher). –  FrustratedWithFormsDesigner Dec 11 '12 at 16:32
3  
@Umer Hassan: then you probably misunderstood him, or he misunderstood the question. –  Michael Borgwardt Dec 11 '12 at 16:32
1  
From this link (docs.oracle.com/javase/tutorial/java/IandI/abstract.html) "...abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods)." –  FrustratedWithFormsDesigner Dec 11 '12 at 16:39

6 Answers 6

An abstract class is a class that cannot be instantiated (i.e. new myAbstractClass()). It is used as a template for other classes to inherit.

An abstract method is a method in an abstract class that can be overridden (i.e. implemented) in a derived class.

The difference between an interface and an abstract class is that you can put functionality in an abstract class (i.e. ordinary or virtual methods) that can be utilized in the derived class, whereas an interface is just an empty template.

share|improve this answer
    
An abstract method must be implemented in a derived class. –  marco-fiset Dec 11 '12 at 18:04
1  
@marco-fiset strictly speaking that's not necessarily - if derived class is abstract as well, implementing is not mandatory –  gnat Dec 11 '12 at 18:17
    
What do you mean by "baseline" or "default" implementation. I was under the impression abstract methods must not have have a method body? Well in c# anyway. Perhaps it varys across languages? –  dreza Dec 12 '12 at 6:45
    
@dreza: Sorry, I meant "virtual." My point was that interfaces do not contain any functionality at all. But, read the two comments above yours. –  Robert Harvey Dec 12 '12 at 15:28

With abstract classes you can have some kind of skeleton for other classes to extend.

You can't instantiate them but you can put some common implementation which you can use in the classes that extend them.

share|improve this answer

A real life example of an abstract class would be Human for example. But would you intantiate a Human object? No! You would further derive classes from the Human abstract class like Infant, Child, Adult, Man, Woman, etc. And you will extend/retrict the original behaviour in these derived classes down in the heirarchy.

share|improve this answer
2  
I don't know, I think Infant, Child, Adult would be better as different states of a Human object, and Man and Woman would be possible values for an enumerated field. –  FrustratedWithFormsDesigner Dec 11 '12 at 16:38
    
If you really want to stick with this example though, you might want to make Hominid your abstract class, maybe with Human and Gorilla as two possible subclasses of it (though I'm not a taxonomist, so maybe this isn't the best way to do it?). –  FrustratedWithFormsDesigner Dec 11 '12 at 16:45
    
I do agree with you partially. We can use overloaded constructors (POLYMORPHISM) for Infant, Child, Adult instead of deriving child classes(INHERITANCE). But what makes you say about Man and Woman to be represented as enumerated fields. Why? They are perfect for to be inherited classes. The example i just gave is for the novice learner. Thanks for your feedback. –  Maxood Dec 11 '12 at 16:46
    
I think Infant, Child, Adult, are better as states, because a human that is an infant will then become a human that is child, then an adult, but it is the same object that is changing state by aging. Man and Woman I think are also better as parts of a state because sometimes a Human that is-a Man could undergo a procedure to become a Woman (and vice-versa) - it's not common but it does happen ;) A model that makes Man and Woman as separate classes is much less flexible, but might be OK depending on what system you're trying to model. –  FrustratedWithFormsDesigner Dec 11 '12 at 16:50

An abstract class is a class that implements some common functionality used by one or more concrete (not abstract) classes.

A good example of this would be the AbstractList class in java. This class is extended by ArrayList (a concrete class) and AbstractSequentialList (an abstract class which is in turn extended by LinkedList).

One would never instantiate an AbstractList (which one do you want? ArrayList? Vector? LinkedList?) and thus it is made abstract to prevent this. However, it implements some internals that are necessary for the functioning of a list (modification count for fail fast).

An abstract method is a method that is not implemented in an abstract class or interface, but must be implemented in the concrete class.

The core reason why one would want to have a method be abstract is to be part of a public API. If you the compareTo method in Comparable is abstract - only the concrete class knows how to implement this correctly for other classes to call.

share|improve this answer

First of all, the examples will be in C#. But I think you'll have no problem understanding it. So...

You CANNOT instantiate objects of an abstract class. You must have a subclass that derives from the class, if you want to instantiate it. But this probably won't help you since you may have come across that before.

So let's try an example.

Suppose you want to lose weight and your nutritionist asks you to track your food intake. When you go to her again, you can't tell her that you ate a "food". Although it's not wrong, since all food has calories, it is too "abstract" for her. So you need to tell her WHICH food.

So, if she were to code that... She'd have an abstract class Food.

abstract class Food
{
    public int CaloriesPerPound { get; set; }
    //...
}

Why? Because that wouldn't allow you to say "I ate a food".

{
    Food fries = new Food(); //This won't even compile
}

So you need concrete classes:

class Fruit : Food
{
 //Other stuff related only to fruits
}

class Bread : Food
{ 
 //Other stuff related only to Bread
}

So you'll have to tell exactly which food it is.

{
   Apple desert = new Apple(); //Now we are talking
}

But she still needs the food class, it is still interesting to her:

class Meal
{
    public List<Food> Foods { get; set; }
    //Other meal related stuff
    public int TotalCalories()
    {
        int calories = 0;
        foreach (Food food in Foods)
        {
            calories = calories + food.CaloriesPerPound * FoodQuantity;
        }
        return calories;
    }
}

That's an example of when you need an abstract class. When you want to have a base class, but you don't want anyone creating an object of your class.

An abstract CAN have abstract methods. It doesn't need to. Is totally ok to have an abstract class without abstract methods. Speaking of which...

Abstract method is something that it's too broad. There's no similarities on how things work, so the classes that derive from your class that has an abstract method won't be able to call the super class implementation. And you're also forcing all the sub classes to implement their version of that method.

Let's try another example? An Animal Band Simulator. You'd have animals, and each one of them would make a sound. But those are very different "implementations", they have nothing in common A dog differs from a cat, a cat from an elephant, an elephant from a cricket. So you'd have an abstract method MakeSound.

class Animal
{
    public abstract void MakeSound();
}

But, if you have an abstract method in your class, that makes the whole class abstract!

abstract class Animal
{
    public abstract void MakeSound();
}

So the rest of the code might be:

class Dog : Animal
{
    public void MakeSound()
    {
        //bark at the moon
    }
}

class Cat : Animal
{
    public void MakeSound()
    {
        //meowing for food
    }
}

And the BAND!

class AnimalBand
{
    public List<Animal> Animals { get; set; }
    public void RockOn()
    {
        foreach (Animal animal in Animals)
        {
            animal.MakeSound();
        }
    }
}

So this is an example of when you use an abstract method.

I guess this is the essence. It may be a little forced/convoluted, but I think it gets the point across. Go back to the examples that didn't help you before and see if they make sense now.

I'm go out on a limb and say you're a beginner. This stuff may seem strange to you, and you may not see any benefit in using abstract classes.

It's ok. It's strange for almost all of us when we start. But in time, you'll learn to appreciate it.

share|improve this answer

An abstract class/method is, conceptually, a "starting point" for a concrete implementation.

An abstract method or other member cannot have any code; it is quite literally a placeholder for a member that must be implemented by classes deriving from the abstract base. It's similar to a method declaration in an interface, but an abstract class can define abstract members of any inheritable visibility, not just public. That abstract member can be used in any code in the abstract class. The purpose is usually to allow the deriving class to specify some implementation-specific logic or behavior, whose extraction from the surrounding code makes that remaining code implementation-independent.

An abstract class cannot be instantiated; it exists to be derived from and to be used as a common type for members and parameters, similar to an interface in this respect. Classes with any abstract members must themselves be marked abstract, but a class with no abstract members can also be marked abstract. Thus, abstract classes can have code in non-abstract members, which is the primary difference from an interface (the other key difference being the ability to define abstract members less visible than "public"). This is a common tactic to share (and thus re-use) code that is common between implementations of the abstract class.

As far as when to use them, succinctly, use an abstract class whenever you would normally use an interface, but when you also wish to define code that can be shared among derived implementations of the base.

There are differing best practices between Java and C# regarding whether to combine interfaces and abstracts in the same inheritance hierarchy. It's been my experience that an interface directly implemented by a single abstract class is redundant in Java due to naming conventions (interface names are supposed to look like class names so coders don't have to care what they're using). In C#, the pattern's still considered a bit "deep" but is more acceptable because the interface, by convention, would be prefaced with "I-". Either way, the arrangement allows even the abstract class to be refactored or replaced without affecting dependent classes; not only can any implementation of an abstract DoerBase be used, but any Doer (or IDoer) including an implementation of a new BetterDoerBase, or a concrete class inheriting directly from the interface.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.