5.1 Declaring classes

Previous Index Next 


 The extends keyword is used in a Java class declaration to indicate that the class inherits from another class. A Java class can only extend one Java class, multiple inheritance is not supported in Java.

For example:

public class Person
 {
  public String name;
  public Date dob;

  public int age()
   {
    //... do age calculation here !
   }
 }

public class Employee extends Person
 {
  public String employeeID;
  public Date startDate;
  public int leaveTaken;
  public int sickDaysTaken;

  public int calculateLeave()
   {
    //... leave calculation goes here
   }
 }
In the code above we have two classes Person and Employee. Employee extends Person it therefore inherits all the public and protected attributes and methods of the Person class. So the following code is legal:
Employee aEmp = new Employee();           // create new Employee object

aEmp.name = "Jonathan Ackerman"           // data fill object
aEmp.dob = new Date(74,4,30);
aEmp.employeeID = "A12345";
aEmp.startDate = new Date(98,2,16);
aEmp.leaveTaken = 0;
aEmp.sickDaystaken = 0;

int age = aEmp.age();                    // calculate age of employee