Inheritance

Optional Node
Collapse Content

One of the principles of OOP is creating Classes that inherit from other Classes. This lets you re-use code, avoid duplication, and helps keep your code more maintainable and extendable. However, it is not essential for beginners, so you can skip this node and return to it at a later point.

Student-Class

Extends keyword
In Java, you use the extends keyword to make a Class a subclass of a superclass. In this case, Student extends Person, which means that Student will "inherit" all of Person's methods and variables. This is why each instance of Student has access to the getName() method, which was defined in Person. Student also defines its own variables and methods, such as SID and getStudentID().

super()
In Java, super is the keyword used in a subclass to refer to the superclass. When used in the constructor, it will call the superclass's constructor. This must be the first method called in the constructor. Java will actually call super() on its own, but it is a good idea to explicitly include it. Also, you will need to call super explicitly if you want to pass parameters to the superclass's constructor (since Java cannot figure out the parameters on its own).

For example, look at the Student's constructors. In each constructor, Student starts off by calling super(), which will invoke Person's constructor:

 Person(String name, int yearOfBirth)
 {
     this.name = name;
     this.yearOfBirth = yearOfBirth;
 }

Student is able to pass in the parameters for name and yearOfBirth to super() for Person to set up. In addition to avoiding code duplication, this is a way of setting up variables that the subclass may not have access to.

Overriding methods
Sometimes the subclass may need to implement a method differently than the way it was implemented by the superclass. In this situation, the subclass can override the method by implementing a method with the same name and header. As a simple example, let's say you have a Class Car with a method accelerate():

class Car
{
  int speed;

  public void accelerate()
  {
    speed = speed + 1;        
  }
}

The subclass RaceCar can override accelerate() with its own method:

public class Racecar extends Car
{    
  public void accelerate()
  {
    speed = speed + 2;
  }
}

If you call accelerate() on a Racecar instance, it will call its own version of the method instead of Car's version, and it will increase the speed by 2.

super in methods
You can call the superclass's available methods from within the subclass in the normal manner. However, if you override a method (such as accelerate() above) then the subclass will call that version instead of the superclass. You can specify a call to the superclass by using the super keyword again:

super.methodName();

This will call the superclass's version of methodName(). This can be useful when you want to override a method to add more code, but you still want it do everything specified by the superclass's method (as was done in the constructor above). For example, look at the method toString() in Student:

public String toString()  // redefined from "Person"
{
  return super.toString() + "ID: " + SID;
}

It starts by calling the Person's version of toString(), and then it adds its own Student-specific details (Student ID).

Subclasses Working Together
Your code can gain many benefits by using inheritance where it fits. Since Student and Staff both inherit from Person, you can handle collections of Persons without worrying whether each Person is a Student or Staff. This is what the Database Class does - it lets you add any type of Person to it. You do not need to write different Database code for adding Students and for adding Staffs.

All Classes are subclasses of Object
As was mentioned earlier, all Classes in Java are really extensions of the Universal Class Object. This means that they all have access to certain methods such as toString(). The default toString() method isn't too useful, which is why many classes override it, as we did above.
Since all Objects use the same toString() method, they can all be handled in a similar manner. To print a list of different Objects, you can iterate through your Object list and call toString() on each Object. In fact, Java even has a shortcut to call toString() - whenever you try printing an Object, it will automatically call that Object's toString() method.

Method Polymorphism
When toString() is called on different Classes, the specific toString() method is called as implemented in that Class. If that Class does not have a toString() method, the code will look at its superclasses until it finds the toString() method. This is known as Method Polymorphism. You can call a method on an Object, and Java will work out which method to call.

This is what the listAll() method of Database does. It simply calls toString() on every object in the database. This will call the toString() method of Student for a Student instance, and the toString() method of a Staff for a Staff instance.

Challenge

The Class Car appears below. Fill in the constructor and accelerate method of the Class RocketCar:

  • constructor - It should call Car's constructor, and also set rocketFuel to 10.
  • accelerate - It should call Car's accelerate method (to run the regular engine), but it should also fire its rocket engine. This means if (and only if) it has rocket fuel left, it should increase the speed by another 2 units and decrease the rocketFuel by 1 unit.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • Is it ok that rocketCar is defined before Car ?

  • @calo, doesn't matter. On a computer, each class is usually defined in its own file; the Java compiler can figure it all out.

  • I see now ...I made it eventually, although to public RocketCar(), I only type formula for rocket fuel and nothing else:
    public RocketCar()
    {
    //constructor

    cont...
  • I can't figure out why fuel stays at 20

  • It is updated

  • Hello.
    I have correct output, but I changed private variables in class car to non-private.
    Is it OK ?
    my code: http://www.learneroo.com/user_answers/5096985764

  • Why, in the Student & Staff example, student1.super.toString() doesn't work? I get Error: cannot find symbol - class student1. I've created an instance of Student called student1.

  • I have:
    if(speed <= maxSpeed && rocketFuel != 0)
    {
    speed+=2;
    rocketFuel--;
    }

    But its saying it doesn't like my maxSpeed...
    Main.java:14: error: maxSpeed has private access in Car
    if(speed <= maxSpeed && rocketFuel != 0)
    ^

    Why?

  • Hi!
    I didn't succeed resolve it..

  • @Raz, you first need to address the compile errors. Don't call super() from within a regular method, instead call super.methodName(). And don't try accessing a Car's private fuel, RocketCar only deals with rocketFuel.

  • I'm didn't understand What am I being asked to do?

  • @Raz, I added a hint that spells it out in order.

  • my code - Didn't work:/

  • You still need to fix your accelerate method, it's not following the correct syntax. See the correct solution for how to fix it.

  • so with this line of code:
    System.out.println(i +". "+ rc);

    when we say + rc it calls the toString() method of class Car?
    can you please explain it why? should't it be something like
    +rc.toString()) ;

  • As mentioned above, Java has a built-in shortcut that calls the toString method of an object when you print it. So System.out.println(i +". "+ rc); is equivalent to System.out.println(i +". "+ rc.toString() );

  • why does super.Car() not work?

  • What method is .Car()?

All Node Comments
Contact Us
Sign in or email us at [email protected]