What is and what is an abstract class for?

Asked

Viewed 34,111 times

36

In object orientation, what is the meaning of an abstract class? What is its purpose?

  • 3

    Any specific language? I think there are small differences from one language to another.

  • 1

    Preferably in Java. But for abstract classes, when it comes to C#, there is some noticeable difference?

  • 15
  • 3

    The question quoted by @mgibsonbr already serves to answer this question.

  • 2

    @Duds, I had mistakenly given -1. I edited your question to remove the negative vote, okay? When you give OK, I remove the comment. + 1

6 answers

43


Abstract classes are classes that are basically just one inspi abstract (with the pardon of the pun) of how the classes that inherit should behave.

Abstract classes cannot be instantiated, as already said, they serve only for other classes to use it as model (inherit their attributes/properties and methods).

They may have abstract or non-abstract methods.
The abstract methods cannot have a body, that is, only the signature of the method should be declared and they obligatorily have to be implemented in the child class (the class that inherits), whereas methods that are not signed as abstract must have the body and may or may not be overwritten in child class.

A very simple example of using an abstract class would be (example in Java)

abstract class Animal{        
    abstract String getHabitat();

    public String getRaca(){
        return "Raça indefinida";
    }
}

class Cachorro extends Animal{
    public String getHabitat(){
        return "";
    }
}

class Gato extends Animal{
    public String getHabitat(){
        return "indefinido";
    }

    public String getRaca(){
        return "Munchkin";
    }
}

In this case, any class you inherit from Animal shall implement the getHabitat(), otherwise a build error will occur. As for the method getRaca(), the child classes can simply use the code that already exists in the abstract class, without worrying about implementing it.

So if you do

Cachorro c = new Cachorro();
System.out.println(c.getRaca()); //A saída será "Raça indefinida"

Gato g = new Gato();
System.out.println(g.getRaca()); //A saída será "Munchkin"
  • Whenever there is an inheritance will there necessarily have to be an abstract class? What can be an example of a "useful" utility of an abstract class? (I mean C++, if there is a difference to java)

  • No need. At least in Java and C# no. Example of useful class goes from the programmer’s need... I can’t think of anything now.

20

The function of an abstract class is to implement partially a type. The best example I know is the class AbstractList Java: while the interface List defines a kind, useful but complex, it does not provide a concrete implementation since there are several ways to implement a list, each with its pros and cons. The ArrayList and the LinkedList are two of them. But nothing prevents the programmer from creating their own lists if necessary.

However, much of what the programmer would have to implement is the same for every list: if you implement a method to add one element to a given position, then you have to implement another to add at the end, another to add several, another to add several at a specific position, etc. It’s too much code to write... And if in the interface you have no concrete implementation (interfaces only serve to define a type), the abstract class allows part of code come ready for you (if you don’t want/can use, just overwrite), and the other part - main - you write yourself.

A simplified example:

// Define um tipo
interface List {
    int size();
    Object get(int indice);
    boolean isEmpty();
    int indexOf(Object o);        
    Iterator iterator();
}

// Implementa parcialmente um tipo
abstract class AbstractList {
    // Esses são os métodos principais, então você é que tem que escrever
    abstract int size();
    abstract Object get(int indice);

    // Esses outros te dão uma "ajuda", fazendo uso do método que você escreveu
    boolean isEmpty() {
        return size() == 0;
    }

    int indexOf(Object o) {
        for ( int i = 0 ; i < size() ; i++ )
            if ( get(i).equals(o) )
                return i;
    }

    Iterator iterator() {
        return new Iterator() {
            int indice = 0;

            boolean hasNext() {
                return indice < size();
            }

            Object next() {
                 return get(indice++);
            }
        };
    }
}

// Implementa um tipo concreto
class ArrayList extends AbstractList {
    Object[] array;

    int size() {
        return array.length;
    }

    Object get(int indice) {
        return array[indice];
    }
}

// Outra implementação
class ListaCom3 extends AbstractList {
    Object obj1;
    Object obj2;
    Object obj3;

    int size() { return 3; }
    Object get(int indice) {
        if ( indice == 0 ) return obj1;
        if ( indice == 1 ) return obj2;
        if ( indice == 2 ) return obj3;
        throw new IllegalArgumentException();
    }
}

Note that the interface (type) requires 5 methods, but with the help of the abstract class each "final" implementation only needs to implement 2.

  • 1

    Very good example @mgibsonbr! Thank you very much!

17

All answers are right. I just want to add a simple information of what the abstract class is.

It is a middle ground between the concrete class and the interface.

It does not fail to have some implementation, that is, it has been (variables) and behavior (methods), including private members, like any other class, but it also has public methods without implementation, or just as contracts, exactly as with interfaces.

As with interfaces, these methods, called abstract, should be implemented in the concrete class that derives from this abstract.

Depending on the situation an abstract class can be used as if it were an interface, since the interface is a purely abstract class (do not fear anything that is not abstract).

Some languages are adopting some abstract class characteristics on interfaces, but not all obviously.

To better understand, I suggest some readings:

  • 1

    I will prefer, just to read these contents.

  • 1

    Thanks a lot @bigown!

9

Abstract classes serve as "models" for other classes that inherit from them, and cannot be instantiated by themselves. To have an object of an abstract class it is necessary to create a more specialized class inheriting from it and then instantiating this new class. The methods of the abstract class must then be superscripted in the child classes.

abstract class Conta { 
    private double saldo; 

    public void setSaldo(double saldo) { 
        this.saldo = saldo; 
    } 

    public double getSaldo() { 
        return saldo; 
    } 

    public abstract void imprimeExtrato(); 
}

9

For better understanding, an abstract class serves as a "model" of inheritance for a concrete class.

Since an abstract class cannot be instantiated by itself, it is necessary, as stated before, to create a concrete extender class from the abstract class. Thus, methods from the abstract class should be superscripted in the "daughter" classes. However, if an abstract class inherits from another abstract class, it is not necessary to implement abstract methods.

Example:

Abstract class:

abstract class Funcionario {

  protected double salario;

  public double getBonificacao() {
    return this.salario * 1.2;
}

Concrete class:

class Gerente extends Funcionario {

  public double getBonificacao() {
    return this.salario * 1.4 + 1000;
  }
}

References: http://www.caelum.com.br/apostila-java-orientacao-objetos/classes-abstracts/#9-3-methodos-abstracts

  • 3

    A doubt, when an abstract class has no abstract method, is it not mandatory to overwrite this method? Only the method superscript will be required when the method is abstract?

  • 3

    Exactly @Duds

  • 5

    It would be lawful to give due Caelum

2

Abstract classes are classes that define the most elementary structure of a class that you can create. They cannot be instantiated, but serve as a basis for creating others from it. The classes that inherit the abstract in question, will have their characteristics, as method and attributes.

Abstract methods cannot have coding, but we must declare them and implement them. The impelled methods must have code and may or may not be superscripted by the heiress class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.