Abstract Classes in Scala (original) (raw)

Last Updated : 31 Oct, 2019

Abstraction is the process to hide the internal details and showing only the functionality. In Scala, abstraction is achieved by using an abstract class. The working of the Scala abstract class is similar to Java abstract class. In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances. A class can extend only one abstract class.Syntax:

abstract class class_name { // code.. }

The abstract methods of abstract class are those methods which do not contain any implementation. Or in other words, the method which does not contain body is known as an abstract method. Syntax:

def function_name()

Example:

Scala `

// Scala program to illustrate how to // create an abstract class

// Abstract class abstract class myauthor {

// abstract method
def details()

}

// GFG class extends abstract class class GFG extends myauthor { def details() { println("Author name: Ankita Saini") println("Topic name: Abstract class in Scala") } }

object Main { // Main method def main(args: Array[String]) { // objects of GFG class var obj = new GFG() obj.details() } }

`

Output:

Author name: Ankita Saini Topic name: Abstract class in Scala

Following are some important observations about abstract classes in Scala.

}
object Main {

// Main method  
def main(args: Array[String]) {  
      
    // Object of myauthor class  
var obj = new myauthor()  
}  

}
` Output:

prog.scala🔞 error: class myauthor is abstract; cannot be instantiated var obj = new myauthor() ^ one error found

}
object Main
{

// Main method  
def main(args: Array[String])  
{  
      
    // objects of GFG class  
    var obj = new GFG()  
    obj.portal()  
    obj.tutdetails()  
}  

}
` Output:
Portal name: GeeksforGeeks
Tutorial name: Scala

{
def details()
}
// GFG class extends abstract class
class GFG(name: String, topic: String) extends
myauthor(name, topic)
{
def details()
{
println("Author name: " + name)
println("Topic name: " + topic)
}
}
object Main
{

// Main method  
def main(args: Array[String])  
{  
      
    // objects of GFG class  
    var obj = new GFG("Ankita", "Abstract class")  
    obj.details()  
}  

}
` Output:
Author name: Ankita
Topic name: Abstract class

}
// GFG class extends abstract class
class GFG extends myauthor{}
object Main
{

// Main method  
def main(args: Array[String])  
{  
      
    // objects of GFG class  
    var obj = new GFG()  
    obj.details()  
}  

}
` Output:
Welcome to GeeksforGeeks

}
` Output:
Final method

**When to use abstract class in Scala:**An abstract class is useful:

**Note:**Traits are also used to achieve abstraction.