I'm writing a program where I create an abstract class Bird. In this class there is a method called chirp() which prints out "chirp". I made an 2 additional classes called Goose and Mallard that extend from Bird with overriding chirp methods that print out different sounds: "Honk" & "Quack". If I was to add another class called Crow that extends from Bird how would I write a method chirp that doesn't overriding?
My approach is to make a method chirp with a different method signature. I think did this but its not compiling as I want it.
Additionally, if I were to make the method in Bird abstract what changes would I need to make to the crow class...
Here is the code I have so far:
import java.util.Scanner; public abstract class Bird { public void chirp() { System.out.println("chirp"); } //if chirp made abstract public abstract void chirp(); } public class Goose extends Bird { public void chirp() { System.out.println("Honk"); } } public class Mallard extends Bird { public void chirp() { System.out.println("Quack"); } } public class Crow extends Bird { String sound; public void chirp(String x) { sound = x; } } public class Problem10 { public static void main(String[] args) { // TODO Auto-generated method stub //Demonstration of polymorphism Bird goose = new Goose(); Bird mallard = new Mallard(); goose.chirp(); mallard.chirp(); //Reference Variable Bird bird = null; //Prompt the user to enter a number that is either 1 or 2 Scanner scanner = new Scanner(System.in); System.out.println("Input number either 1 or 2: "); int inputInt = scanner.nextInt(); if (inputInt == 1) { bird = new Goose(); } else if (inputInt == 2) { bird = new Mallard(); } else if (inputInt == 3) { bird = new Crow(); bird.chirp("Crow"); } bird.chirp(); } }
Crow#chrip(String)does not overrideBird#chip(), sinceCrow#chirpadded a parameter that does not exist inBird#chirp. You would have to remove the parameter, or rethink your design