Major OOP concepts in Java

Reading Time: 2 minutes

Abstract classes and abstraction

This is a way of hiding implementation & ignoring the body of a method. The method bodies will be filled in derived classes. Remember the base class has to add “abstract” modifier in all of the provided methods  and the derived methods from the base class have to have the same access modifier.

BaseClass:

public abstract class BaseClass {

    public abstract void run();

    abstract void stop();
}

DerivedClass

public class DerivedClass extends BaseClass {
    @Override
    public void run() {
        System.out.printf("Running...");
    }

    @Override
    void stop() {
        System.out.printf("Stopped!");
    }
}

Inheritance

This way can be clarified as an object inherits additional methods from the corresponding derived/extended object. This is achieved by using “extends” keyword example shown below

Creating a variable pf the derived c;ass to access its own objects

Employee

class Employee {

    String name;
    String address;
    String phoneNumber;
    float experience;

    public void attendTraining() {

    }

    public void receiveSalary(){
        System.out.println("has salary received");
    }
}

Programmer

class Programmer extends Employee {

String[] programmingLanguages;

void writeCode() {
System.out.printf("writing code");
}

}

Office

public class Office {

    public static void main(String[] args) {
        Programmer programmer = new Programmer();
        programmer.name = "Tugrul";
        programmer.address = "Turkey";
        programmer.phoneNumber = "009000000000";
        programmer.experience = 10;

        programmer.receiveSalary();

        programmer.writeCode();

        programmer.programmingLanguages = new String[] {"Java", "C++"};

        for(String obj : programmer.programmingLanguages){
            System.out.printf(obj);
        }

    }
}

Output

Name: Tugrul
Address: Turkey
Phone Number: 009000000000
Experience: 10.0
salary received
writing code
Java
C++

Creating a variable of the base class to access an object of a derived class

This is to create an Employee object of the HRExecutive object. There is no compilation error because HRExecutive object is the child class of Employee this means there is an “IS-A” relationship.

As you will notice Employee object will only reach its own objects not HRExecutive’s properties.

Office

class Office {
public static void main(String args[]) {
Employee emp = new HRExecutive();
emp.name="Tugrul";
System.out.println(emp.name);
}
}

Output

Tugrul

Here you see emp instance can only reach employee properties, not HRExecutive object’s properties.