Inheritance

And interactions with OOP

What is Inheritance in Java?

Now that we have covered Objects in Java, let's talk about inheritance. Everyone knows that Technology is a very broad list of things. We also know that Digital Devices are a kind of technology (such as computers, tablets, and televisions). We also know that Cameras are a type of digital device. If we were to implement such objects in Java, we could create three separate classes (one for Technology, DigitalDevice, and Camera). However, there is an easier way to do this, and it saves a lot of unnecessary duplicate work. This method is called inheritance.


Since we know that a Camera is a kind of Digital Device, we can say that Camera extends DigitalDevice. By doing so, all the attributes and methods that are able to be performed by a DigitalDevice will be inherited by the Camera subclass. The below code is the implementation of the Camera and DigitalDevice example:

public class DigitalDevice {

private String name;

private int yearManufactured;

private String model;

private String ownerName;

public void sell(String newOwner) {

ownerName = newOwner

}

}


public class Camera extends DigitalDevice {

private int lensSize;

public void takePicture() {

// takes a picture

}

}

As you can see, the Camera class has been made as a subclass of DigitalDevice. Now, if we were to make an object of Camera, we can also use the sell() method that was inherited from the DigitalDevice class.

public class Driver {

public static void main(String[] args) {

Camera myCamera = new Camera();

myCamera.takePicture(); // from the Camera class

myCamera.sell("Tim"); // from the DigitalDevice class

}

}

The benefits of inheritance is that it allows the user of the program and the programmer him/herself to be able to be more organized when following along with the program. It also makes the programming easier since it helps avoid duplicate work when creating fields or methods in a subclass.

Overriding methods

A programmer can also override a method in a superclass in a subclass by declaring a method with the same name and parameters in the subclass. A common example is the toString() method in the Object class, and every class in Java inherits this method. By default the method would give the address of the object in memory, so we could override the method by making a new toString() method in a subclass. Here is an example:

public class Person {

private String name;

private int age;


public Person(String n, int a) {

name = n;

age = a;

}


// The "Override" tag can be added to signify an

// overriding of a superclass method


@Override

public String toString() {

return "This person, " + name + " is " + age +

"years old."

}

}

This way, whenever we print a Person object using System.out.println(), the default toString() method will no longer be used. Instead, the overridden method that we just implemented will be used.