Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using abstract classes instead of traits?

Tags:

scala

traits

What is the advantage of using an abstract class instead of a trait (apart from performance)? It seems like abstract classes can be replaced by traits in most cases.

like image 208
Ralf Avatar asked Jan 02 '10 09:01

Ralf


People also ask

What is the benefit of using abstract class?

The abstract class in Java enables the best way to execute the process of data abstraction by providing the developers with the option of hiding the code implementation. It also presents the end-user with a template that explains the methods involved.

What are the advantages of abstract class over non abstract class?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

What is the difference between a trait and an abstract class?

Trait supports multiple inheritance. Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance.

Why should we use abstract class instead of normal class?

The only reason for declaring a class as abstract is so that it can't be instantiated. There are situations where you will have common functionality that is shared between a number of classes, but by itself that common functionality does not represent an object or represents an incomplete object.


1 Answers

I can think of two differences

  1. Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. There was some discussion that in future even traits can have constructor parameters
  2. Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Traits are fully interoperable only if they do not contain any implementation code
like image 62
Mushtaq Ahmed Avatar answered Sep 28 '22 05:09

Mushtaq Ahmed