Inheritance
When a class inherits from another, it means it extends another. We use the ‘extends’ keyword for this. The class that extends is the subclass, the child class, or the derived class. The other class is the superclass, the parent class, or the base class.
Syntax of Scala Inheritance
To carry out Scala inheritance, we use the keyword ‘extends’:
class Student extends Person(){
/*your code goes here*/
}
Examples :
class Person{
var SSN:String="999-32-7869"
}
class Student extends Person{
var enrolment_no:String="0812CS141028"
}
object Inheritance {
def main(args:Array[String]): Unit ={
var stud = new Student;
println("SSN: "+stud.SSN)
println("Enrolment Number: "+stud.enrolment_no)
}
}
//Output
SSN: 999-32-7869
Enrolment Number: 0812CS141028
To carry out Scala inheritance, we use the keyword ‘extends’ and 'with':
trait Person{
var SSN:String="999-32-7869"
}
trait Government{
var voterID:Int = 12342
}
class Student extends Person with Government {
var enrolment_no:String="0812CS141028"
}
object Inheritance {
def main(args:Array[String]): Unit ={
var stud = new Student;
println("SSN: "+stud.SSN)
println("Enrolment Number: "+stud.enrolment_no)
println("Voter ID number : " +stud.voterID)
}
}
//Output
SSN: 999-32-7869
Enrolment Number: 0812CS141028
Voter ID number : 12342
No comments:
Post a Comment