Inheritance and class extensions – Java Tutorial

Inheritance and class extensions – Java Tutorial

Inheritance is where you can apply a general category to a more specific one. If you remember back in Lesson Three, we used the constructor Student oneStudent = new Student(). This is how inheritance works. We could also type Student studentTwo = new Student() and Student thirdStudent = new Student() to add two more students to the Student constructor. However, once you get a good hand on Java and go into the business industry, the program that’s going to get used is the one just like yours, only it takes up less memory space because it used less programming code. Why keep reinventing the wheel when you don’t have to? Inheritance allows you to inherit bits and pieces of programs from other programs. It also allows you to develop programs more quickly and with less errors because these bits and pieces have already been used and tested. The class Student would be considered the base class (also superclass or parent class), and ShowStudent would be a derived class (also subclass or child class).In Lesson Eight and Nine, we use extends to inherit the attributes from the Applet class. Similarly, you can use extends to extend to any class. This means there is a superclass-subclass relationship between Student and ShowStudent. Here’s how:

public class Student
{
  private int idNumber;
  private int hoursEarned;
  private double pointsEarned;
  private double pointAverage;
  Student()
  {
    idNumber = 42;
    hoursEarned = 3;
    pointsEarned = 3.5 * hoursEarned;
    pointAverage = pointsEarned / hoursEarned;
  }
  public int getIdNumber()
  {
    return idNumber;
  }
  public int getHoursEarned()
  {
    return hoursEarned;
  }
  public double getPointsEarned()
  {
    return pointsEarned;
  }
  public double getPointAverage()
  {
    return pointAverage;
  }
  public void setIdNumber(int n)
  {
    idNumber = n;
  }
  public void setHoursEarned(int hrs)
  {
    hoursEarned = hrs;
  }
  public void setPointsEarned(double pts)
  {
    pointsEarned = pts;
  }
  public void setPointAverage(double ave)
  {
    pointAverage = ave;
  }
}

Inheritance and class extensions

Above is the Student program that you’ll be using as your base class. Typical programs can be longer or shorter than the one we’re using. Next, we’ll look at ShowStudent:

public class ShowStudent extends Student
{
  private int socSecNum;
  public int getSocSecNum()
  {
    return socSecNum;
  }
  public void setSocSecNum(int num)
  {
    socSecNum = num;
  }
}

ShowStudent extends itself to Student and uses whatever codes Student has to share. This way, it has direct access to Student’s get() and set() methods. Only the sublcass (derived or child) can inherit from a superclass (base or parent), not the other way around, kind of like mother to son. Now, if you want to use the Student items in ShowStudent, you could type:

ShowStudent firstStudent = new ShowStudent();

Once you have instantiated this object, you can use any of the Student objects by typing:

firstStudent.pointsEarned(2);

When you use a subclass to create methods, those methods override the methods in the superclass. This type of action is called polymorphism, where there are many forms that the same word can take depending on the object associated with the word. For instance, if you had another class named PrintStudents, you could add a method to ShowStudent and PrintStudent that looks like this:

public void printStudentInfo()
{
  System.out.println("Social Security Number: ");
}

After adding this method to each class, you call them in the same way you called firstStudent. To make sure that we haven’t lost anyone, below are three programs that show how inheritance works. This first program sets up how an order will be placed and what fields will be required.

public class Order
{
  private String customerName = "A Johnson";
  private int idNum = 23654;
  private int quantityOrdered = 2;
  private double unitPrice = 8.95;
  protected double totalPrice = quantityOrdered * unitPrice;
  // getCustomerName() gets customerName
  public String getCustomerName()
  {
    return customerName;
  }
  // getIdNum() gets idNum
  public int getIdNum()
  {
    return idNum;
  }
  // getQuantityOrdered() gets quantityOrdered
  public int getQuantityOrdered()
  {
    return quantityOrdered;
  }
  // getUnitPrice() gets unitPrice
  public double getUnitPrice()
  {
    return unitPrice;
  }
  // setCustomerName() sets customerName
  public void setCustomerName(String name)
  {
    customerName = name;
  }
  // setIdNum() sets idNum
  public void setIdNum(int num)
  {
    idNum = num;
  }
  // setQuantityOrdered() sets quantityOrdered
  public void setQuantityOrdered(int qty)
  {
    quantityOrdered = qty;
  }
  // setUnitPrice() sets unitPrice
  public void setUnitPrice(double price)
  {
    unitPrice = price;
  }
  public void computeTotalPrice()
  {
    totalPrice = quantityOrdered * unitPrice;
    System.out.println("Total price: $" + totalPrice);
  }
}

Notice that totalPrice is “protected” instead of “public” or “private”. This means that totalPrice is only able to be used by the program it’s in and any programs that extend from it. This next program extends the first, then adds shipping and handling.

public class OrderShipping extends Order
{
  private double shipHandleCharge = 4.00;
  public void computeTotalPrice()
  {
    totalPrice += shipHandleCharge;
    System.out.println("Total price with S & H: $" + totalPrice);
  }
}

Now, if you’ll notice that this is not only a smaller version of Order but it also extends it, so it doesn’t need to have all the rest of Order‘s program retyped. If you were to print the file size of the two, OrderShipping would be larger because of the inheritance. This next program calls and executes both programs.

public class Billing
{
  public static void main(String[] args)
  {
    Order anOrder = new Order();
    OrderShipping anotherOrder = new OrderShipping();
    anOrder.computeTotalPrice();
    anotherOrder.computeTotalPrice();
  }
}

Question: There’s got to be more than that. Isn’t there any rules or guidelines that need to be followed?

Answer: Yes, there is. Next we’ll learn how to use superclasses and subclasses.