DEV Community

Otu Michael
Otu Michael

Posted on • Updated on

A Simple Introduction To Java - Object Oriented Programming - Part 2

In this session, we will discuss:

In the previous chapter, we discussed the Shape class and the concept of Encapsulation. The Shape class can be summarized as:

  • length: double
  • breadth: double
  • area(): double
  • perimeter(): double
  • print(): void

We said that:

Encapsulation means data hiding, making use of the private keyword which restricts access to fields or and methods declared as private.

Inheritance

Squares, Rectangles, Circles, and others are plane figures or shapes. We defined the Shape class with the above fields and methods. Can you implement a class for Square, rectangle, Circle, etc without some or all the fields and methods? Of course, you can.

What is the point of Inheritance?

When given two classes say class A and B. if class B happens to share the same fields and methods as class A, then in the implementation of class B we would only have to create a class for the class that will have all the fields and methods of class A then we'd add the fields and methods that are not available in class A.

So in Inheritance, one class will have the fields and methods of another class. That is it.

The common terms one hears of most often are inheritance, extending, sub-classing and others (create a class based on another class).

Super and Sub Class

A super class, also known as a parent or a base class, is the class from which other classes are created. In science class, we had fundamental quantities like mass, length, time, etc. We then derive other quantities such as velocity and her friends.

A sub class, also known as a child or a derived class, is the class that is created/derived from another. From science class, we had derived quantities like area, volume, and velocity and her brothers were created from a combination of other quantities such as length, time, etc.

Extending A Class

Given a class A:

public class A {

}
Enter fullscreen mode Exit fullscreen mode

Another class B will inherit the properties of class A as:

public class B extends A {

}
Enter fullscreen mode Exit fullscreen mode

So to extend a class we use the extends keyword.

Create the Human-Student-Teacher class

Is there any difference between a student and a teacher? Are there features and abilities one has over the other? Are there any similarities between them?

Let's see some similarities.

  • Full name or just name
  • Date of birth
  • Both are hairy in some way or the other
  • They would have their IDs
  • etc

Let's see some distinctions.

  • A teacher is a stuff of the school and a student is not. A teacher can teach the class but a student can't do that.
  • A teacher receives a salary at the end of the month but the student has to pay fees for the academic year.
  • etc

The idea is that we group the attributes that both have and we create a class for that. Then each entity will inherit that parent class and add its attributes and methods.

A teacher and a student are both human so we can create a class called Human that can serve as the base class.

// Human.java
public class Human {

    private String id;
    private String password;
    private String fullName;

    public Human() {
    }

    public Human(
        String id, 
        String password, 
        String fullName) {
        this.id = id;
        this.password = password;
        this.fullName = fullName;
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFullName() {
        return this.fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
}

Enter fullscreen mode Exit fullscreen mode

Now, the Human class doesn't need much elaboration. We can create a Student class without creating a constructor (we'd use the default/empty constructor).

// Student.java
public class Student extends Human {

    public Student() {
    }

}
Enter fullscreen mode Exit fullscreen mode

In the Main class, we can use the getter and setter methods to manipulate the properties of the Student object that we will create.

// Main.java
public class Main {

    public static void main(String[] args) {
        Student student = new Student();

        // set the properties of the class using
        student.setId("std0012");
        student.setFullName("John Adams");
        student.setPassword("simple_password");

        System.out.println(
            "Full Name: " + student.getFullName());
        System.out.println("ID: " + student.getId());
        System.out.println(
            "Password: " + student.getPassword());
    }
}
Enter fullscreen mode Exit fullscreen mode

You know, we can also add a constructor to the Student class so that it will have the same constructor signature as its parent class. We can achieve this by calling the constructor of the parent class. We don't have to redefine the properties that are defined in the parent class. We just have to pass them as parameters. To achieve this, we can use the super function that java provides. We will use the super function as a normal constructor.

// Main.java
public class Student extends Human {

    public Student() {
    }

    public Student(
        String id, 
        String password, 
        String fullName) {
        super(id, password, fullName);
    }

}
Enter fullscreen mode Exit fullscreen mode

And now, our Main class will look like

// Main.js
public class Main {

    public static void main(String[] args) {
        // set the properties of the class using
        /*
         * Student student = new Student();
         *
         * student.setId("std0012");
         * student.setFullName("John Adams");
         * student.setPassword("simple_password");
         */

        // Use the student constructor
        Student student = new Student(
            "std0012", 
            "simple_password", 
            "John Adams");

        System.out.println(
            "Full Name: " + student.getFullName());
        System.out.println("ID: " + student.getId());
        System.out.println(
            "Password: " + student.getPassword());
    }
}
Enter fullscreen mode Exit fullscreen mode

What happens in super(id, password, fullName);?

This is the same as calling the constructor of the super class and passing in the necessary arguments.

Let's say we want to add a new property to the Student class, we can do so simply as:

// Student.java
public class Student extends Human {

    private boolean isClassRep;

    public Student() {
    }

    public Student(
        String id, String password, String fullName) {
        super(id, password, fullName);
    }

    // new constructor with a fourth parameter for isClassRep
    public Student(
        String id, 
        String password, 
        String fullName,
        boolean isClassRep) {
        super(id, password, fullName);

        // not added to super
        this.isClassRep = isClassRep; 
        // same as the above
        // this.setClassRep(isClassRep); 
    }

    public boolean isClassRep() {
        return this.isClassRep;
    }

    public void setClassRep(boolean isClassRep) {
        this.isClassRep = isClassRep;
    }

}
Enter fullscreen mode Exit fullscreen mode

As we can see, I add a new property, isClassRep and created a new constructor which allows us to pass the new property as part of the Student constructor. I did that so that we can still maintain the parent signature.

// Main.java
public class Main {

    public static void main(String[] args) {
        // set the properties of the class using
        /*
         * Student student = new Student();
         *
         * student.setId("std0012");
         * student.setFullName("John Adams");
         * student.setPassword("simple_password");
         */

        // Use the student constructor
        Student student = new Student(
            "std0012", "bunny", "John Adams");

        System.out.println(
            "Full Name: " + student.getFullName());
        System.out.println("ID: " + student.getId());
        System.out.println(
           "Password: " + student.getPassword());
        System.out.println();

        // student object with isClassRep
        Student studentRep = new Student(
            "std0013", "password", "Hannah Adams", true);

        System.out.println(
            "Full Name: " + studentRep.getFullName());
        System.out.println("ID: " + studentRep.getId());
        System.out.println(
            "Password: " + studentRep.getFullName());
        System.out.println(
            studentRep.getFullName() 
            + " is class president: " 
            + studentRep.isClassRep());
    }
}
Enter fullscreen mode Exit fullscreen mode

You can create the Teacher class that extends the Human class. Add an attribute for isClassTeacher: boolean, and also the teacher's salary, salary: int.

What would we do if we want to add an attribute to the class called hobby: String? Try it out.

Conclusion

One class may share the properties and methods of another class through Inheritance. In java, we use the extends keyword to indicate that a class is being inherited. The class whose methods and attributes are inherited is called the super class and the class which does the inheriting is called the sub class. We can make use of the constructor of the super class using the super keyword and then passing the necessary arguments.

Projects

Let's consider the one-dimensional shape class, Shape. Inherit this class and create the Square and Rectangle sub classes with the appropriate attribute(s) and methods to:

  • describe(): void -> to describe the shape
  • area(): int -> to return the area of the said shape
  • perimeter(): int -> to return the perimeter of the said shape
// Shape.java
public class Shape {
    private int side;

    public Shape(int side) {
        this.side = side;
    }

    public int getSide() {
        return this.side;
    }

    public void setSide(int side) {
        this.side = side;
    }

}
Enter fullscreen mode Exit fullscreen mode

Source

  • Sololearn
  • DS Malik
  • vscode (code generation)

Top

Discussion (1)

Collapse
xinusys profile image
XinuSys

Easy to understand examples, well-written intro to O.O.P. ✔