Inheritance Proposal

I am doing a lesson that should demonstrate inheritance using the song Old MacDonald; There is an interface for animals, a farm class that implements each animal object. You get the idea. I have two problems.

1) The animal has a type and sound, for example, a chicken

class Chick implements Animal {
    private String myType;
    private String mySound;
    private String mySound2;
    int flag =0;

    public Chick(String type, String sound)
    {
        myType = type;
        mySound = sound;
    }

    public Chick(String type, String sound,String sound2)
    {
        myType = type;
        mySound = sound;
        mySound2=sound2;
    } 

    public Chick()
    {
        myType = "unknown";
        mySound = "unknown";
    }

    public String getSound() 
    {
        return mySound;
    }

    public String getType()
    {
        return myType; 
    }
}

I have to create a second constructor with a flag that says the chicken is childish and returns the sound “cheep”, or is an adult, and returns “cluck” to get equal probability of getSound (). I do not know how to do that. I considered adding a boolean to the constructor, but this will not work because the farm class can only create a new Chick (); I understand that you will not just give me the answer, but I don’t even know where to start.

2) , NamedCow, , , , , .

getName cow, namedCow

public class NamedCow extends Cow {

    private String myName;

    NamedCow(String name)
    {
        myName = name;
    }

    public String getName()
    {
        return myName;
    }

Chick Cow ? ?

+4
1

Chick , : http://docs.oracle.com/javase/7/docs/api/java/util/Random.html

nextBoolean() getSound (boolean isChild)

getSound()

if (isChild)
   return "cheep";
else 
   return "cluck";

.

String getSound(){

Random r = new Random();

if (r.nextBoolean)
       return "cheep";
    else 
       return "cluck";
}

, , , : , - :

nameCow(String name){
    this.cowName=name;
}
0

Source: https://habr.com/ru/post/1532363/


All Articles