Open In App

Extending a Class in Scala

Last Updated : 23 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Extending a class in Scala user can design an inherited class. To extend a class in Scala we use extends keyword. there are two restrictions to extend a class in Scala :

  • To override method in scala override keyword is required.
  • Only the primary constructor can pass parameters to the base constructor.
  • Syntax:

    class derived_class_name extends base_class_name
    {
        // Methods and fields
    }
    

    Example:




    // Scala program of extending a class
      
    // Base class 
    class Geeks1
        var Name: String = "chaitanyashah"
      
    // Derived class 
    // Using extends keyword 
    class Geeks2 extends Geeks1
        var Article_no: Int = 30
          
        // Method 
        def details() 
        
            println("Author name: " + Name); 
            println("Total numbers of articles: " + Article_no); 
        
      
    // Creating object
    object GFG 
          
        // Driver code 
        def main(args: Array[String]) 
        
              
            // Creating object of derived class 
            val ob = new Geeks2(); 
            ob.details(); 
        

    
    

    Output:

    Author name: chaitanyashah
    Total numbers of articles: 30
    

    In the above example Geeks1 is the base class and Geeks2 is the derived class which is derived from Geeks1 using extends keyword. In the main method when we create the object of Geeks2 class, a copy of all the methods and fields of the base class acquires memory in this object. That is why by using the object of the derived class we can also access the members of the base class.

    Example:




    // Scala program of extending a class
      
    // Base class
    class Parent 
        var Name1: String = "geek1"
        var Name2: String = "geek2"
      
    // Derived from the parent class 
    class Child1 extends Parent 
        var Age: Int = 32
        def details1() 
        
            println(" Name: " + Name1)
            println(" Age: "  + Age) 
        
      
    // Derived from Parent class 
    class Child2 extends Parent 
        var Height: Int = 164
          
        // Method 
        def details2() 
        
            println(" Name: " + Name2
            println(" Height: " + Height) 
        
      
    // Creating object
    object GFG 
          
        // Driver code 
        def main(args: Array[String]) 
        
              
            // Creating objects of both derived classes 
            val ob1 = new Child1(); 
            val ob2 = new Child2(); 
            ob1.details1(); 
            ob2.details2(); 
        

    
    

    Output:

    Name: geek1
    Age: 32
    Name: geek2
    Height: 164
    

    In the above example Parent is the base class Child1 and Child2 are the derived class which is derived from Parent using extends keyword. In the main method when we create the objects of Child1 and Child2 class a copy of all the methods and fields of the base class acquires memory in this object.
    Example:




    // Scala program of extending a class
      
    // Base class
    class Bicycle (val gearVal:Int, val speedVal: Int)
    {
        // the Bicycle class has two fields 
       var gear: Int = gearVal
       var speed: Int = speedVal
         
       // the Bicycle class has two methods 
       def applyBreak(decrement: Int)
       {
           gear = gear - decrement
           println("new gear value: " + gear);
       }
       def speedUp(increment: Int)
       {
           speed = speed + increment;
           println("new speed value: " + speed);
       }
    }
      
    // Derived class
    class MountainBike(override val gearVal: Int, 
                        override val speedVal: Int,
                        val startHeightVal : Int) 
                        extends Bicycle(gearVal, speedVal)
    {
        // the MountainBike subclass adds one more field 
       var startHeight: Int = startHeightVal
         
       // the MountainBike subclass adds one more method 
       def addHeight(newVal: Int)
       {
           startHeight = startHeight + newVal
           println("new startHeight : " + startHeight);
       }
    }
      
    // Creating object
    object GFG 
    {
        // Main method
        def main(args: Array[String]) 
        {
            val bike = new MountainBike(10, 20, 15);
      
            bike.addHeight(10);
            bike.speedUp(5);
            bike.applyBreak(5);
        }
    }

    
    

    Output:

    new startHeight : 25
    new speed value: 25
    new gear value: 5
    

    In above program, when an object of MountainBike class is created, a copy of the all methods and fields of the superclass acquire memory in this object.



Similar Reads

How to Access a Case Class Method from Another Class in Scala?
Accessing a case class method from another class in Scala can be achieved through several approaches. Case classes are commonly used to model immutable data and provide convenient methods for accessing and manipulating data fields. The article focuses on discussing different methods to access a case class method from another class in Scala. Table o
2 min read
Class and Object in Scala
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities. Class A class is a user-defined blueprint or prototype from which objects are created. Or in other words, a class combines the fields and methods(member function which defines actions) into a single unit. Basically, in a class construc
5 min read
Inner class in Scala
Inner class means defining a class into another. This feature enables the user to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code. In Scala, the concept of inner classes is different from Java. Like in Java, the inner class is the member of the out
3 min read
Scala | Case Class and Case Object
Explanation of Case Class A Case Class is just like a regular class, which has a feature for modeling unchangeable data. It is also constructive in pattern matching. It has been defined with a modifier case, due to this case keyword, we can get some benefits to stop oneself from doing a sections of codes that have to be included in many places with
4 min read
Calling A Super Class Constructor in Scala
Prerequisite - Scala ConstructorsIn Scala, Constructors are used to initialize an object's state and are executed at the time of object creation. There is a single primary constructor and all the other constructors must ultimately chain into it. When we define a subclass in Scala, we control the superclass constructor that is called by its primary
3 min read
Scala - Generating Boilerplate Code With Case Class
Scala Case classes come shipped in with many handy methods. The Scala compiler generates boilerplate code when a case class is defined. This does away with writing redundant code which otherwise developers need to write for normal classes. Some of the methods that are generated as boilerplate code are as follows: setter getter apply() unapply() toS
4 min read
Determine the class of a Scala object
To determine the class of a Scala object we use getClass method. This method returns the Class details which is the parent Class of the instance. Below is the example to determine class of a Scala object. Calling method with argument - Example #1: // Scala program to determine the class of a Scala object // Creating object object Geeks { // Using g
2 min read
Call a method on a Super Class in Scala
This concept is used when we want to call super class method. So whenever a base and subclass have same named methods then to resolve ambiguity we use super keyword to call base class method. The keyword "super" came into this with the concept of Inheritance. Below is the example of call a method on a superclass. Example #1: // Scala program to cal
2 min read
How to clone a Case Class instance and change just one field in Scala?
Using the copy function that case classes offer, you may clone an instance of a case class in Scala and modify a single field. You may create a new instance of a case class with updated fields while maintaining the integrity of the other fields by using the copy method that case classes automatically produce. Utilizing the Copy MethodScala case cla
1 min read
Scala short <(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short <(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
How to Install Scala IDE For Eclipse?
In this tutorial, we'll look at how to set up the Eclipse IDE for Scala. This tutorial is for those who are new to Scala. Requirement for InstallationEclipse (Install link) if you don't know how to install Eclipse then refer to this article.JDK 11 (you may use JDK 6 onwards) Note: If you do not have JDK installed, you may get them from this link. I
2 min read
Scala Map size() method with example
The size() is utilized to find the number of key-value pairs in the stated map. Method Definition: def size: Int Return Type: It returns the number of elements in the map. Example #1: // Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks
1 min read
Scala SortedMap addString() method with a start, a separator and an end with example
This method is same as addString() method but here a start, a separator and an end is also included. Method Definition: def addString(sb: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder Where, sep is the separator stated. Return Type: It returns the elements of the SortedMap in the String Builder and a start,
2 min read
Scala Iterator addString() method with example
The addString() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It is utilized to append the elements of the Scala Iterator to a String Builder. Method Definition : def addString(b: StringBuilder): StringBuilder Return Type : It returns the String Builder to which the elements
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Scala | Functions Call-by-Name
In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function. Here example are shown with difference and sy
3 min read
Program to convert Java list to an iterator in Scala
A java list can be converted to an iterator in Scala by utilizing toIterator method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# C/C++ Code // Scala program to convert Java lis
3 min read
Scala Set &() method with example
The &() method is utilized to create a new set consisting of all elements that are present in both the given sets. Method Definition: Return Type: It returns a new set consisting of all elements that are present in both the given sets. Example #1: // Scala program of &() // method // Creating object object GfG { // Main method def main(args
1 min read
Scala | Type Inference
Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly. Let us first have a look at
4 min read
Program to convert Java set of Shorts to an Indexed Sequence in Scala
A java set of Shorts can be converted to an Indexed Sequence in Scala by utilizing toIndexedSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert
2 min read
Scala Int <(x: Char) method with example
The <(x: Char) method is utilized to return true if the specified int value is less than the char value, otherwise returns false. Here the char value is the ASCII value of the specified char. Method Definition: (Int_Value).<(Char_Value)Return Type: It returns true if the specified int value is less than the char value, otherwise returns false
1 min read
Article Tags :