Class (object orientation)

from Wikipedia, the free encyclopedia
Example class Employee (top) with two instances (bottom right and left).

In object-oriented programming, a class (also called an object type ) is an abstract model or a construction plan for a series of similar objects .

The class serves as a blueprint for mapping real objects into software objects and describes attributes (properties) and methods (behaviors) of the objects. Generally speaking, one could also say that a class corresponds to the data type of an object. From a formal point of view, a class does not occupy any working memory at program execution time , but only the objects that it instantiates .

Inheritance

Classes can have hierarchical relationships with one another and become complex structures. The principles by which these are formed describe the basic concept of inheritance . The terms base class and derived class are also important here in order to characterize the relationships between the classes. The base class describes general properties and is therefore a generalization of the derived classes. These are therefore specializations of the basic class.

For example, the base class Kraftfahrzeugis a generalization of the derived classes (specializations) Auto, LKW, Motorradand Traktor.

While inheriting the classes derived all the properties and methods of the base class (d. E., A motorcycle has all the characteristics of a motor vehicle, and you can do with it, can you do with a car). In addition, the derived class introduces additional properties and methods that are possible with its objects . The motorcycle has z. B. a luggage rack, not a car, but a trunk.

Programming style

In many programming languages it is common for the name of a class to begin with an uppercase letter, while the names of the variables begin with a lowercase letter.

Composite

Similar to the class, the compound is a tool for managing attributes that belong together. It is a composite data type from various other data types. The individual components can be viewed as attributes of the new composite type. Depending on the programming language , the network and the class can differ to a greater or lesser extent. Examples of differences are:

  • Own methods and which types are possible
  • Memory management
  • Behavior on assignment (reference only, shallow copy , deep copy)
  • Usability and definability of standard operators
  • Inheritance
  • Support for visibilities that do not publichave
  • Support from unions
  • Types of types permitted as attributes (classes, compound types, simple types)

Examples

C #

Take a lamp as an example . A lamp can have different properties (attributes), for example color, weight and whether it lights up. Since one can hardly operate with the properties of color and size, a sensible behavior would be a light switch method that determines the respective status of on and off.

Example implementation in C # :

class Lampe {
    // Eigenschaften
    Color gehaeusefarbe;
    double gewicht;
    Color lichtfarbe;
    double helligkeit;
    bool istEingeschaltet;

    // Methoden
    void einschalten() {
        istEingeschaltet = true;
    }

    void ausschalten() {
        istEingeschaltet = false;
    }
}

The concept of inheritance can be demonstrated by the fact that there are different types of lamps, e.g. B. street lamps, flashlights or car headlights. These particular types of lamps are then subclasses of the class Lampe; H. they have additional attributes (e.g. Taschenlampe.maximaleLeuchtdauer, Autoscheinwerfer.istKippbar) and methods (e.g. Taschenlampe.batterieLaden(), Autoscheinwerfer.fernlichtEinschalten()). The attributes and methods of the class Lampeare adopted and also apply to the subclasses. For these special classes, the class is Lampea base class .

In C # :

// Unterklassen der Klasse Lampe

class Taschenlampe : Lampe {
    // zusätzliche Eigenschaften
    double maximaleLeuchtdauer;

    // zusätzliche Methoden
    void batterieLaden() {
        // Implementierung der Methode
    }
}

class Autoscheinwerfer : Lampe {
    // zusätzliche Eigenschaften
    bool istKippbar;

    // zusätzliche Methoden
    void fernlichtEinschalten() {
        // Implementierung der Methode
    }
}

A class can be used as a data type (for example, attributes or. Methods - Parameters ).

Example: A parliament consists of several members who Personare and are mostly members of one Partei. The class Abgeordneteris implemented as a subclass of the class Person. Each parliament has a member as chairman. The class Parlamentcan setzeVorsitzenden(...)define a method with this Abgeordneteras a parameter; it sets the attribute vorsitzenderto the specified "value". In addition, a method is gibAnzahlDerAbgeordneten(...)implemented which Parteireceives a parameter of the class and returns the number of members of this party.

Possible C # implementation:

class Person {
    // Eigenschaften
    string vorname;
    string nachname;
    Date geburtsdatum;
    List<string> nationalitaeten;
    string MailAdresse;
    string Postanschrift;
}

class Partei {
    // Eigenschaften
    string name;
    List<Person> mitglieder;
}

// Unterklasse der Klasse Person
class Abgeordneter: Person {
    // Eigenschaften
    Partei partei;

    // Methoden
    Partei gibPartei() {
        return partei;
    }
}

class Parlament {
    // Eigenschaften
    Abgeordneter vorsitzender;
    int maximalGroesse;

    // Liste von Objekten der Klasse Abgeordneter
    List<Abgeordneter> listeAbgeordnete = new List<Abgeordneter>();

    // Methoden
    void setzeVorsitzenden(Abgeordneter abgeordneter) {
        vorsitzender = abgeordneter;
    }

    int gibAnzahlDerAbgeordneten(Partei partei) {
        int anzahl = 0;
        
        foreach (Abgeordneter einAbgeordneter in listeAbgeordnete) {
            if (einAbgeordneter.gibPartei() == partei) {
                anzahl = anzahl + 1;
            }
        }

        return anzahl;
    }
}

Ruby

The following example is written in the Ruby programming language:

# Die Klasse "Fahrzeug" ist die Basisklasse.
class Fahrzeug
    def bewegen()
        puts "Fahrzeug wird bewegt."
    end
end

# Die Klasse "Auto" ist die abgeleitete Klasse.
class Auto < Fahrzeug
    def bewegen()
        puts "Auto wird bewegt."
    end
end

def fahren(fahrzeug)
    # zur Verdeutlichung der sog. "Polymorphie"
    fahrzeug.bewegen()
end

# Hauptprogramm
fahrzeug = Fahrzeug.new
auto = Auto.new

fahrzeug.bewegen()
auto.bewegen()

# Polymorphie: Methode 'fahren'
fahren(fahrzeug)
fahren(auto)

This program defines a class Fahrzeugand a class derived from it Auto.

The base class has a method called bewegen()that prints the text “Vehicle is moving” on the computer screen. The Fahrzeugclass derived from Autoalso has a method bewegen()and overrides the method from Fahrzeug. The output it generates is “Car is moved”.

This is followed by the definition of an independent function fahren()that receives an object of the base class as an argument. The method is bewegen()called on this object .

Finally, the main program follows, which creates both an object of the base class ( fahrzeug) and the derived class ( auto), and first bewegen()calls both and then executes it fahren()again bewegen()for both objects with the help of .

If this program is executed, the following appears on the screen:

Fahrzeug wird bewegt.
Auto wird bewegt.
Fahrzeug wird bewegt.
Auto wird bewegt.

It can be seen that although the function is defined fahren()for a Fahrzeug, it also works for a Autoand the overridden method is called; that is, it works for objects of the base class as well as for objects of all derived classes. These inherit the properties and thus “can” everything that the base class “can”. This generally desirable behavior is called polymorphism .

extension

An extension or abstraction of this concept can be found in the model of the abstract classes and the metaclasses .

A so-called anonymous class is also possible . A class is only described at the exact point at which an object is created by it. It is not described separately (for example in its own file) as an independent component in the source code and therefore cannot be reused or specifically addressed by other parts of the program. The class does not have its own name either. Usually, however, it inherits from another, which then describes the main properties and methods of the object for its later use. The derived, nameless class usually only modifies the behavior slightly.

An example in Java :

import java.awt.Button;
import java.awt.event.ActionListener;

// Erzeugen eines Button-Objekts, speichern in hilfeButton
// "Hilfe" ist die Beschriftung des Buttons
Button hilfeButton = new Button("Hilfe");

// Zum Button wird ein Objekt hinzugefügt, das eine Methode "actionPerformed"
// besitzt. Die Methode wird aufgerufen, wenn der Button angeklickt wird.
hilfeButton.addActionListener(
    new ActionListener() {
        void actionPerformed(ActionEvent e) {
            System.out.println("Hilfetext");
        }
    } // end anonymous class
);

It is with newan object created, the main thing in a java.awt.event.ActionListenercorresponding (though no base class , but Interface ). As a special behavior for precisely this object , the method actionPerformed is overwritten so that it is displayed Hilfetexton the screen. Since a specialized behavior has been defined, the object is of a derived class , i.e. not of ActionListenerdirect - but no class name was specified. In the following program, the object can only be ActionListenerused as (see polymorphism ).

Sometimes an inner class is defined similar to an anonymous class . The difference to a “normal” class is first of all the visibility area , an inner class is defined within another (“outer class”). If it is private, only objects of the outer class can create and use objects of the inner class. If the inner class is non-static, an object generation is even dependent on an object of the outer class and only possible via such an object.

reflection

Some programming languages allow a program to know the structure of its classes and also to change classes at runtime , such as changing the structure by adding or removing properties or methods . This so-called “ reflection ” should only be used in an emergency, as it makes the program difficult to understand and makes refactoring difficult.

See also

literature

  • Laura Lemay, Rogers Cadenhead: Java in 21 days. Markt & Technik, book and software publishing house, Munich 2000, ISBN 3-8272-5578-3 .
  • Peter Pepper: Learn to program. A basic introduction to Java. 3. Edition. Springer, Berlin et al. 2007, ISBN 978-3-540-72363-9 .
  • Katharina Morik, Volker Klingspor: Computer science compact: A basic introduction to Java. Springer, Berlin et al. 2006, ISBN 3-540-24304-6 .

Web links

Wikibooks: Object Oriented Programming (PHP)  - Learning and Teaching Materials