Matura: Softwareentwicklung & Informationssysteme

2.3. dynamische Bindung, Polymorphie, überschreiben/überladen

Dynamische Bindung

class School {
    public void ringBell() {
        System.out.println("Ringing the school bell...");
    }
}
class Classroom extends School {
    @Override
    public void ringBell() {
        System.out.println("Ringing the classroom bell...");
    }
}
class Main {
    public static void main(String[] args) {
        School s1 = new School(); //Type is School and object is of School
        s1.ringBell();
        Classroom c1 = new Classroom(); //Type is Classroom and object is of Classroom
        c1.ringBell();
        School s2 = new Classroom(); //Type is School and object is of Classroom
        s2.ringBell();
    }
}

/* Output:
Ringing the school bell...
Ringing the classroom bell...
Ringing the classroom bell...
*/

Methoden (Signatur, Parameter, Überschreiben (Override), Overload)

Signatur

Überschreiben (@Override)

class ParentClass {
	public void displayMethod(String msg) {
		System.out.println(msg);
	}
}
class SubClass extends ParentClass {
	@Override
	public void displayMethod(String msg) {
		System.out.println("Message is: "+ msg);
	}

	public static void main(String args[]) {
		SubClass obj = new SubClass();
		obj.displayMethod("Hey!!");
	}
}

/* Output:
Message is: Hey!!
*/

Overload

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Polymorphie

Statische Polymorphie

Dynamische Polymorphie

Tier[] tiere = {
    new Vogel(),
    new Wurm()
};

for (int i = 0; i < tiere.length; i++) {
    tiere[i].bewegtSich(); //einmal bewegtSich() von Vogel, einmal bewegtSich() von Wurm
}

Generics (<>, z.B Task/Service, Collections)

HashSet<Person> personen = new HashSet<>();