ADVERTISEMENT
ADVERTISEMENT

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

Problem Solution:

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

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.

Scala Inheritance Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.