Search code examples
javascala

Getting Abstract error in method in Scala


I am getting error: sound method can't be abstract. But, when I remove 'abstract', I get class Dog and Cat needs to be abstract. What am I doing wrong?

The task says that class Dog and Cat should remain concrete. Task is below.

package inheritance

abstract class Animal(name: String) {
  abstract def sound(): String

  override def toString(): Animal
}

class Cat(var name: String)
  extends Animal(name) {
  override def sound() = {
    "meow"
  }
}

class Dog(var name: String)
  extends Animal(name) {
  override def sound() = {
    "woof"
  }
}

object Park {
  def animals() = {
    List(new Dog("Snoopy"), new Dog("Finn"), new Cat("Garfield"), new
        Cat("Morris"))
  }

  def makeSomeNoise(first: List[Animal]): List[String] = first.map(_.sound())
}

Task:

Question: [Scala] In a package named "inheritance" create an abstract class named "Animal" and concrete classes named "Cat" and "Dog".

Create an object named "Park":

Animal: A constructor that takes a String called name (Do not use either val or var. It will be declared in the base classes);

An abstract method named sound that takes no parameters and returns a String

• Override toString to return the name of this Animal

Cat: Inherent Animal; A constructor that take a String called name as a value (use val to declare name); Override sound() to return "meow

"Dog: Inherent Animal; A constructor that take a String called name as a value (use val to declare name); Override sound() to return "woof"

Park:
• A method named "animals" that take no parameters and returns a list of animals containing

• 2 dogs with names "Snoopy" and "Finn"

• 2 cats with names "Garfield" and"Morris"

• A method named "makeSomeNoise" that takes a list of animals as a parameter and returns a list of strings containing the noises from each animal in the input list


Solution

  • OK, let's tackle a few of these.

    An abstract method named sound that takes no parameters and returns a String

    The modifier abstract is only used on class definitions. An abstract method is a method within an abstract class, and that method has no body, only the name and types are presented.

    Override toString to return the name of this Animal

    You haven't done this. Currently your toString method is also abstract.

    Cat: Inherent Animal; A constructor that take a String called name as a value (use val to declare name); Override sound() to return "meow"

    It says here to use val but your code has var.

    So the reason you're having problems with Cat and Dog is because Animal, as you currently define it, has two abstract methods and you need to implement (override) both to create an instance of the animal.

    Fix the toString method so that it is no longer abstract, and returns the correct result, and you should be good to go.