3.6 Object Oriented Programming
Abstract Classe
Abstract Classes define unimplemented values that subclasses must implement.
Abstract class can’t be instantiated.
A class can only directly inherit from one parent abstract class.
1
class MyClass extends HasTrait1
1 | abstract class MyAbstractClass { |
Trait
Define unimplemented values like abstract class.
Traits class can’t be instantiated.
Difference:
- A class can inherit from multiple traits.
1
class MyClass extends HasTrait1 with HasTrait2 with HasTrait3
- (?) A trait cannot have constructor parameters.
1 | trait HasFunction { |
Object
- You can simply directly reference it
- Object can’t be instantiated**. **(no need to call
new
)
Companion Object
Companion object and class share the same name and defined in the same file.
When you use
new
before the class/object name, it will instantiate the class.If you don’t use
new
, it will reference the object.
1 | object Lion { |
Companion objects are usually used for the following reasons:
to contain constants related to the class
to execute code before/after the class constructor
to create multiple constructors for a class
1 | object Animal { |
- Chisel uses many companion objects, like Module. When you write the following you are calling the Module companion object.
1 | val myModule = Module(new MyModule) |
Case Class
- Allows external access to the class parameters.
- Eliminates the need to use
new
when instantiating the class.
This is because the Scala compiler automatically creates a companion object for every case class in your code, which contains an apply method for the case class.
- Automatically creates an unapply method that supplies access to all of the class Parameters.
- Cannot be subclassed from.
1 | class Nail(length: Int) // Regular class |
Inheritance with Chisel
Every Chisel module you make is a class extending the base type
Module
.Every Chisel IO you make is a class extending the base type
Bundle
(or, in some special cases,Bundle
‘s supertypeRecord
).Chisel hardware types like
UInt
orBundle
all haveData
as a supertype.