Inheritance

Description:

Inheritance: one class can inherit fields and methods from its superclass.

extends: keyword used to inherit the properties of a class. 

When to useInheritance is to be used when you have multiples of classes that have very similar or the same functionalities/ Attributes.

Exmaple:

Super class:

public class Employee {

    private String name;
    private int id;
    
    public Employee(String name, int id){
        this.name = name;
        this.id = id;
    }
    
    public void printInfo(){
        System.out.println("Employee Name: " + name + ","+ " Employee ID: " + id);
    }
}

Sub class:

public class John extends Employee {
    String company;
    public John(String name , int id){
        super(name, id);
        this.company = company
    }

    public void printCompany(){
        System.out.println("Employees Company is "+ company);
    }
}

Main class:

public class Main {
    public static void main(String [] args){
        
        John john = new John("John", 12345);
        john.printInfo();
        john.printCompany();
    }
}

Results:

Employee Name: John, Employee ID: 12345
Employees Company is Mekonah.com

Challenge Problem

Leave a Reply