ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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

Problem Solution:

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.

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.

Scala Inheritance Programs »

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

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.