Constructors, Inheritance, and Abstraction
November 26, 2019 Leave a comment
Class Parameters vs Class Fields
Parameters passed in the class constructor cannot be accessed on the instance unless they are marked ‘val’ whereas
Fields can be accessed directly on the instance.
class Person(name: String, val age: Int) { // instance level functionality // name is Class Parameter // age is class Field } val person = new Person("ntallapa", 23) println(person.age) // is valid because age is class field and hence can be accesses directly on the object println(person.name) // Invalid as parameters cannot be directly accessed
Primary Constructor, Secondary/Auxiliary Constructors
Constructor defined inline with the class definition is the primary constructor.
Auxiliary constructors can only invoke primary constructors with some default values.
class Person(name: String, val age: Int) { // Primary Constructor def this(name: String) = this(name, 0) // Auxiliary constructor }
If there is is mismatch in number of constructor args between parent and child class, we should mention it explicitly otherwise the JVM default behavior is to look at same number constructor in the parent class
// constructors class Person(name: String, age: Int) // class Adult(name: String, age: Int, idCard: String) extends Person // the above stmt will not work as there is no 3-arg constructor in Person class Adult(name: String, age: Int, idCard: String) extends Person(name, age) // is the correct way
Auxiliary constructors are really not much useful in Scala.
There are 3 Specifiers (conceptually similar to Java)
- private
- protected
- none (public)
Inheritance
Single inheritance can be achieved via extends keyword (extending classes and abstract classes) and multiple inheritance is achieved via “with” keyword on Traits
Abstract Classes and Traits
Unlike in Java, we can have both abstract and non-abstract members in Abstract Class and also in Trait
Differences
traits cannot have constructor parameters
we can only extend one class but inherit multiple traits
traits are a type of a behavior whereas abstract class is a type of thing
What is a sealed class/trait in scala?
A sealed class/trait can only be extended within the same file and not possible to extent outside of the file.
Recent Comments