Java brei Sleutelwoord uit
Voorbeeld
Die Car
klas (subklas) erf die eienskappe en metodes van die Vehicle
klas (superklas):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Definisie en gebruik
Die extends
sleutelwoord brei 'n klas uit (dui aan dat 'n klas van 'n ander klas geërf word).
In Java is dit moontlik om eienskappe en metodes van een klas na 'n ander te erf. Ons groepeer die "erfeniskonsep" in twee kategorieë:
- subklas (kind) - die klas wat van 'n ander klas erf
- superklas (ouer) - die klas waarvandaan geërf word
Om van 'n klas te erf, gebruik die extends
sleutelwoord.
Verwante bladsye
Lees meer oor oorerwing in ons Java-oorerwingtutoriaal .