a)Add interface ISound with method Sound() to the project
Add class Cat with fields: name,color and properties for accessing these fields.
Class Cat should implement interface ISound - method Sound should write cat-sound ("M'yau")
Add class Dog with similar members as Cat class.
b) In the method Main() create array of ISound type and fill it with Cats and Dogs objects.
Output the sound of this array in for each loop by calling method Sound for each element;
package LessonsFromC.Homework3.AnimalSounds;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestAnimalSounds {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<ISound> array = new ArrayList<ISound>();
for(int i = 0; i<2; i++)
{
String catName = sc.next();
String dogName = sc.next();
ISound cat = new Cat(catName);
ISound dog = new Dog(dogName);
array.add(cat);
array.add(dog);
}
System.out.println(array);
for(ISound sound : array){
sound.Sound();
}
}
}
_______________________
package LessonsFromC.Homework3.AnimalSounds;
public interface ISound {
public void Sound();
}
______________________
package LessonsFromC.Homework3.AnimalSounds;
public class Dog implements ISound{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Dog(String theName){
this.name = theName;
}
@Override
public void Sound() {
System.out.println("Gav!");
}
public String toString() {
return this.getName();
}
}
______________________
package LessonsFromC.Homework3.AnimalSounds;
public class Cat implements ISound{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void Sound() {
System.out.println("M'yau");
}
public String toString() {
return this.getName();
}
}
Немає коментарів:
Дописати коментар