Scala program to implement hybrid inheritance

Here, we are going to learn how to implement hybrid inheritance in Scala programming language?
Submitted by Nidhi, on June 09, 2021 [Last updated : March 11, 2023]

Scala - Hybrid Inheritance Example

Here, we will implement hybrid inheritance by combining multilevel and hierarchical inheritance.

Scala code to implement hybrid inheritance

The source code to implement hybrid inheritance is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to implement hybrid inheritance

class A {
  var numA: Int = 0;

  def setA(n: Int) {
    numA = n;

  def printA() {
    printf("numA: %d\n", numA);

class B extends A {
  var numB: Int = 0;

  def setB(n: Int) {
    numB = n;

  def printB() {
    printf("numB: %d\n", numB);

class C extends B {
  var numC: Int = 0;

  def setC(n: Int) {
    numC = n;

  def printC() {
    printf("numC: %d\n", numC);

class D extends A {
  var numD: Int = 0;

  def setD(n: Int) {
    numD = n;

  def printD() {
    printf("numD: %d\n", numD);

object Sample {
  def main(args: Array[String]) {
    var obj1 = new C();
    var obj2 = new D();






numA: 10
numB: 20
numC: 30
numA: 40
numD: 50


In the above program, we used an object-oriented approach to create the program. Here, we created an object Sample.

Here, we created five classes "A", "B", "C", "D", "E". And, we inherited class "A" into "B" and "D" classes. The class "B" is inherited into "C".

Then we defined the main() function in the Sample object. The main() function is the entry point for the program.

In the main() function, we created the objects of the "C" and "D" class and then set and print values on the console screen.

Scala Inheritance Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.