Q:

Scala program to implement hybrid inheritance

belongs to collection: Scala Inheritance Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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();

    obj1.setA(10);
    obj1.setB(20);
    obj1.setC(30);

    obj1.printA();
    obj1.printB();
    obj1.printC();

    obj2.setA(40);
    obj2.setD(50);

    obj2.printA();
    obj2.printD();
  }
}

Output:

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

Explanation:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to demonstrate the protected access ... >>
<< Scala program to implement hierarchical inheritanc...