Scala program to demonstrate the protected access specifier

Here, we are going to demonstrate the protected access specifier in Scala programming language.
Submitted by Nidhi, on June 09, 2021 [Last updated : March 11, 2023]

Scala - Protected Access Specifier Example

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.

Scala code to demonstrate the example of protected access specifier

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.

Scala Inheritance Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.