- 定义一个Animal类(包名cn.edu.ahtcm.model)要求如下
(1)定义成员变量:名称name,体重weight,颜色color,成员变量定义为私有的,同时生成相应的get和set方法;
(2)包括void动态方法run()(输出“Animal run fastly”);void eat()(输出“Animal eat something”),以及受保护的叫方法shout()(输出“Animal shout”)
(3)定义重载方法run(String name),输出谁跑得快
(4)包括有参构造方法
(5)重写toString()方法,实现打印输出成员变量的值;
(6)在main方法里新建一个对象a(new调用构造方法),然后打印输出a的各个成员变量,再通过set方法改变name值,再调用两个run方法和eat方法
package cn.edu.antcm.model;
public class Animal {
private String name;
private double weight;
private String color;
public Animal(String name){
this.name = name;
}
public void setName(String aniName){
name = aniName;
}
public void getName(){
System.out.println("名字:" + name);
}
public void setWeight(double aniWeight){
weight = aniWeight;
}
public void getWeight(){
System.out.println("体重:" + weight);
}
public void setColor(String aniColor){
color = aniColor;
}
public void getColor(){
System.out.println("颜色:" + color);
}
public void run(){
System.out.println("Animal run fastly");
}
public void run(String name){
System.out.println( name + " run fastly");
}
public void eat(){
System.out.println("Animal eat something");
}
protected void shout(){
System.out.println("Animal shout");
}
public String toString(){
return "名称:" + name + "重量:" + weight + "颜色:" + color;
}
public static void main(String[] args){
Animal a = new Animal("a");
a.setWeight(25);
a.setColor("black");
System.out.println(a);
a.setName("cat");
a.run();
a.run("cat");
a.eat();
}
}
2.定义一个Dog类(包名cn.edu.ahtcm.model)要求如下
(1)继承父类Animal,增加新的成员变量:种类category
(2)有参构造方法
(3)重写父类的run()方法(输出“dog run fastly”);eat()(输出“dog love bone”)
(4)在main方法里新建一个对象d1(new调用构造方法,Dog d1 = new ….),然后打印输出的d1的run和eat方法
(5)在main方法里新建一个对象d2(new调用构造方法, Animal d2 = new ….),然后打印输出的d2的run和eat方法,观察java的多态
(6)将d2 强制转换为Dog类型,并使用关键字instanceof判断d2是否是Dog类型,如果是打印输出d2的种类值。
package cn.edu.antcm.model;
public class Dog extends Animal {
String category;
public Dog(String name, String category) {
super(name);
this.category = category;
}
public void run() {
System.out.println("dog run fastly");
}
public void eat() {
System.out.println("dog love bone");
}
public static void main(String[] args) {
Dog d1 = new Dog("zy","dog");
Animal d2 = new Dog("hjg","bird");
d1.run();
d1.eat();
d2.run();
d2.eat();
Dog d3;
d3 = (Dog)d2;
if (d2 instanceof Dog)
System.out.println(d3.category);
}
}