Q:

Scala program to demonstrate the protected access specifier

belongs to collection: Scala Inheritance Programs

0

Here, we will demonstrate a protected access specifier. The protected members can be accessed in the derived class. But a private member cannot be accessed in the derived class.

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 demonstrate the protected access specifier is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate the
// "protected" specifier

class A {
  private var num1: Int = 0;
  protected var num2: Int = 0;
}

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

  def setB(n1: Int, n2: Int, n3: Int) {
    //Private member cannot be accessed in inheritance
    //num1=n1;

    num2 = n2;
    num3 = n3;
  }

  def printB() {

    //Private member cannot be accessed in inheritance
    //printf("Num1: %d\n",num1);

    printf("Num2: %d\n", num2);
    printf("Num3: %d\n", num3);
  }
}

object Sample {
  def main(args: Array[String]) {
    var obj = new B();

    obj.setB(10, 20, 30);
    obj.printB();
  }
}

Output:

Num2: 20
Num3: 30

Explanation:

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

Here, we created two classes "A" and "B". Then we inherited the class "A" into class "B". The private members of class "A" cannot be accessed in derived class "B". Only protected members are accessible.

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 object of class "B" 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 implement method overriding... >>
<< Scala program to implement hybrid inheritance...