「Java学习打卡」33、面向对象程序练习

题目要求:

  1. 定义一个抽象类Person,包含抽象方法eat(),封装属性name、sex、age,声明包含三个参数的构造方法;
  2. 定义一个Chinese类,继承自Person类,重写父类的eat()方法,并定义一个自己特有的方法shadowBoxing();
  3. 定义一个English类,继承自Person类,重写父类的eat()方法,并定义一个自己特有的方法horseRiding();
  4. 编写测试类,定义一个showEat()方法,使用父类作为方法的形参,实现多态,分别调用showEat()方法,通过强制类型转换调用各自类特有的方法;
package case2;
import java.util.Scanner;
public class Task2 {
     
	public static void main(String[] args) {
     
        Scanner sc = new Scanner(System.in);
        String cName = sc.next();
        String cSex = sc.next();
        int cAge = sc.nextInt();
        String eName = sc.next();
        String eSex = sc.next();
        int eAge = sc.nextInt();
        Person person1=new Chinese(cName,cSex,cAge);
        showEat(person1);
        Person person2=new English(eName,eSex,eAge);
        showEat(person2);
        Chinese c = (Chinese)person1;
        ((Chinese) person1).shadowBoxing();
        English e = (English)person2;
        ((English) person2).shadowBoxing();
    }

    public static void showEat(Person person){
     
        if(person instanceof Chinese){
     
            Chinese c = (Chinese)person;
            c.eat();
        }else if (person instanceof English){
     
            English e = (English)person;
            e.eat();
        }
    }
}

abstract class Person {
     
    public String name;
    public String sex;
    public int age;
    public Person(String n,String s,int a){
     
        this.name=n;
        this.sex=s;
        this.age=a;
    }
    public void eat(){
     

    }
}

class Chinese extends Person {
     
    public Chinese(String n, String s, int a) {
     
        super(n, s, a);
    }
    public void eat(){
     
        System.out.println("姓名:"+name+",性别:"+sex+",年龄:"+age+",我是中国人,我喜欢吃饭!");
    }
    public void shadowBoxing(){
     
        System.out.println(""+name+"在练习太极拳!");
    }
}

class English extends Person {
     
    public English(String n, String s, int a) {
     
        super(n, s, a);
    }
    public void eat(){
     
        System.out.println("姓名:"+name+",性别:"+sex+",年龄:"+age+",我是英国人,我喜欢吃三明治!");
    }
    public void shadowBoxing(){
     
        System.out.println(""+name+"在练习骑马!");
    }
}

你可能感兴趣的:(「Java学习打卡」33、面向对象程序练习)