KaiquanMah's picture
class SubClass1 extends ParentClass { }
0376331 verified
raw
history blame
1.44 kB
In Java, each class can DIRECTLY INHERIT UP TO 1 CLASS.
In fact, in Java, every class inherits (unless otherwise specified) the PARENT CLASS 'Object'.
Thus, all Java classes are DIRECT OR INDIRECT heirs of the class 'Object'.
Inheritance is indicated by the keyword 'extends'.
In fact, the English version is perhaps clearer in meaning than inheritance:
the INHERITING/CHILD class 'extends' the functionality of the PARENT class,
since new properties can be added to the child class in addition to those of the parent class.
As an example, let us first consider the class 'Person'.
The class constructor is currently empty, we will return to this later:
class Person {
private String name;
private String email;
// CONSTRUCTOR - EMPTY
public Person() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Now you can define the class Student, which inherits the Person class.
So the Student class has all the features of the Person class (but no new implementation of its own yet).
class Student extends Person { }
Similarly, a class Teacher can be defined, which also inherits the Person class.
The teacher now also has all the attributes of a person:
class Teacher extends Person { }