07: Scala Factory Method Pattern & Trait Vs Abstract classes

This extends the Scala Class Vs. Object and Companion object interview Q&As to implement the factory method.

Q1. What is a factory method pattern?
A1. It is an Object Oriented Programming design pattern to instantiate objects. For example, if a “Person” is an abstract class where a person can be an “Employee” or a “Customer”, we can implement the factory method as shown below:

Output:

In Scala, the factory method pattern is implemented using Singleton Object and Pattern Matching.

Scala does not have an interface concept like in Java, but has a more powerful trait, which defines all required functions.

Q2. What is the difference between a Scala trait and an abstract class?
A2. Both trait & abstract classes provide a collection of reusable behaviour.

TraitAbstract class
Traits support multiple inheritanceAbstract class does not support multiple inheritance
An object instance can have a trait added to it.An object instance cannot have an abstract class added to it.
Do not contain constructor parameters.Contain constructor parameters.
Super calls are dynamically bound.Super calls are statically bound.
Completely inter-operable with Java only when they do not contain any implementation codeCompletely inter-operable with Java code

Q3. How will you implement a Person class with a default function say nameLength() that is common to both Employee & Customer?
A3. An abstract class is useful when you want to add constructor parameters as demonstrated below:

Output:


Categories Menu - Q&As, FAQs & Tutorials

Top