Bsp.: Überschreiben von Methoden
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...
*/
@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!!
*/
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
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
}
<>
gekennzeichnet<>
kann bei der Verwendung eine beliebige Klasse eingegeben werden<>
steht Variablenname, z.B. < E >
HashSet<Person> personen = new HashSet<>();