How it comes that I instantiate an abstract class?
abstract class A {
val a: Int
}
val a = new A {val a = 3}
Or is some concrete class implicitly created? And what do those braces after new A
mean?
An abstract class can also contain only non- abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited. As shown in the below program. In Scala, an abstract class can contain final methods (methods that cannot be overridden).
Abstract class is used to achieve abstraction. Abstraction is a process in which we hide complex implementation details and show only functionality to the user. In scala, we can achieve abstraction by using abstract class and trait.
To implement Scala abstract class, we use the keyword 'abstract' against its declaration. It is also mandatory for a child to implement all abstract methods of the parent class. We can also use traits to implement abstraction; we will see that later.
An abstract class can extend another abstract class. And any concrete subclasses must ensure that all abstract methods are implemented.
With this, you implicitly extend A
. What you did is syntactic sugar, equivalent to this:
class A' extends A {
val a = 3
}
val a = new A'
These brackets merely let you extend a class on the fly, creating a new, anonymous class, which instantiates the value a
and is therefore not abstract any more.
If you know Java, this is similar to:
new SomeAbstractClass() {
// possible necessary implementation
}
Due to Scalas uniform access it looks like you're not implementing any abstract functions, but just by giving a
a value, you actually do "concretesize" the class.
In other words, you're creating an instance of a concrete subclass of A
without giving the subclass a name (thus the term "anonymous" class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With