01E: 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.

Trait Abstract class
Traits support multiple inheritance Abstract 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 code Completely 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:


800+ Java Interview Q&As Menu

Learn by categories on the go...
Learn by categories such as FAQs – Core Java, Key Area – Low Latency, Core Java – Java 8, JEE – Microservices, Big Data – NoSQL, Architecture – Distributed, Big Data – Spark, etc. Some posts belong to multiple categories.
Top