小新看到朋友养宠物非常羡慕,自己也想养宠物,小新开始准备养一只老虎,被妈妈揍了一顿,于是他只好养了一条狗狗,计划再养猫猫,或者鹦鹉等等,请通过代码完成这个过程。
Xiaoxin wanted to keep a pet. Xiaoxin started to prepare to keep a tiger. His mother beat him up, so he had to keep a dog. He planned to keep a cat or a parrot again. Please complete this process through the code.
public class Main {
public static void main(String[] args) {
Student xiaoxin = new Student();
xiaoxin.feedPet(new Dog("小汪"));
xiaoxin.feedPet(new Cat("小白"));
}
}
class Student{
public void feedPet( 【】){
pet.beFriendly();
pet.beAccompanied();
}
}
//定义接口
【】 IPet{
void beFriendly();
void beAccompanied();
}
//定义抽象类
【】 class Animal{
private String name;
//定义抽象方法
public 【】 void move();
public Animal(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//继承animal 实现IPet
class Cat 【】{
public Cat(String name){
【】
}
//实现beFriendly方法
//实现be beAccompanied方法
@Override
public void move() {
// TODO Auto-generated method stub
System.out.println("cat move quiently");
}
}
//继承animal 实现IPet
class Dog 【】{
public Dog(String name){
【】
}
//实现beFriendly方法
//实现be beAccompanied法
@Override
public void move() {
// TODO Auto-generated method stub
System.out.println("dog move quickly");
}
}
输入格式:
输出格式:
输入样例:
在这里给出一组输入。例如:
输出样例:
在这里给出相应的输出。例如:
i am 小汪 dog, i am friendly
i am 小汪 dog, i can talk a walk with you
i am 小白 cat, i am friendly
i am 小白 cat, i can accompany you quiently
package test;
public class Main {
public static void main(String[] args) {
Student xiaoxin = new Student();
Dog dog =new Dog("小汪");
xiaoxin.feedPet(dog);
// xiaoxin.feedPet(new Dog("小汪"));
xiaoxin.feedPet(new Cat("小白"));
}
}
class Student{
public void feedPet(IPet pet){ //定义接口IPet pet***
pet.beFriendly();
pet.beAccompanied();
}
}
//定义接口
interface IPet{
void beFriendly();
void beAccompanied();
}
//定义抽象类
abstract class Animal{
private String name;
//定义抽象方法
public abstract void move();
public Animal(String name) {
super(); //!!
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//继承animal 实现IPet
class Cat extends Animal implements IPet{
public Cat(String name){
super(name);
}
//实现beFriendly方法
public void beFriendly(){
System.out.println("i am 小白 cat, i am friendly");
}
//实现be beAccompanied方法
public void beAccompanied(){
System.out.println("i am 小白 cat, i can accompany you quiently");
}
@Override
public void move() {
// TODO Auto-generated method stub
System.out.println("cat move quiently");
}
}
//继承animal 实现IPet
class Dog extends Animal implements IPet{
public Dog(String name){
super(name);
}
//实现beFriendly方法
public void beFriendly(){
System.out.println("i am 小汪 dog, i am friendly");
}
//实现be beAccompanied法
public void beAccompanied(){
System.out.println("i am 小汪 dog, i can talk a walk with you ");
}
@Override
public void move() {
// TODO Auto-generated method stub
System.out.println("dog move quickly");
}
}
总结: super();调用父类的构造方法 定义接口类型用的少不是很理解,还需要往后面学在来看多练多看多写多想