2

I'm getting a bit confuse on the queue example on two things:

Question 1: Why BasicIntQueue's methods does not have the override keyword.

Here's the example code:

abstract class IntQueue { def get(): Int def put(x: Int) } import scala.collection.mutable.ArrayBuffer class BasicIntQueue extends IntQueue { private val buf = new ArrayBuffer[Int] def get() = buf.remove() def put(x: Int) { buf += x } } 

Shouldn't it be:

//class BasicIntQueue ... override def get() = buf.remove() override def put(x: Int) { buf += x } 

I've implemented with override and the expected result is the same.

Question 2: Why super in traits?

trait Doubling extends IntQueue { abstract override def put(x: Int) { super.put(2 * x) } } class MyQueue extends BasicIntQueue with Doubling 

I've tried it without the super keyword and it failed. I've drawn a UML diagram but have sort of fuzzy reasoning why.

 abstract override def put(x: Int) { super.put(2 * x) } 

This line of Doubling method overrides BasicInQueue's method? If so why would we need super? Why can't we just do:

 abstract override def put(x: Int) { 2 * x } 

For me, the above line would just override the BasicInQueue's method with a new put implementation? The abstract override keyword is for some sort of stack manipulation at run time only right? Why do we need the super anyway? What is the super referring to? Whatever that is on the left? So with BasicIntQueue with Doubling, is the super keyword in Doubling referring to BasicIntQueue?

Thank you, for your time.

1 Answer 1

6

For Question 1, IntQueue is declared as abstract and the methods are virtual. Therefore the BasicIntQueue is not overriding methods, but rather supplying the required implementations. If the methods in IntQueue had bodies, then BasicIntQueue would need the override keyword on its methods.

For Question 2, the super is referring to the method that the trait's method is overriding. The trait requires that the class has a put method defined, but instead of completely replacing it, it augments it by doubling the value sent to it.

abstract override def put(x: Int) { 2 * x } 

will not work because it doesn't actually put anything in the queue, in fact since the function is Unit (returns nothing) it doesn't do anything at all.

abstract override def put(x: Int) { super.put(2 * x) } 

takes the value sent to put, doubles it, and then calls the original put method to actually add it to the queue.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.