(1)创建一个Java工程;
(2)创建Mammal类,设置属性weight, height, legs, tail,对它们显式初始化,而且将它们的访问控制权限分别设为public、protected、default和private。定义方法printWeight()、printHeight()、printLegs()、printTail(),每个方法的访问控制权限依次是public、protected、default和private,每个方法中只有一条输出语句,如printWeight()方法中的语句是System.out.println(“ The weight is: ”+weight);其他类似。
(3)创建Cat类,作为Mammal类的子类。重写printWeight()方法,其中的语句是System.out.println(“ The weight of the cat is: ”+weight);
(4)创建测试类Test作为主类,并且在main()方法中创建Mammal类的对象,把引用赋值给Mammal类型的变量animal,使用它来访问Mammal类中定义的每个成员,观察代码窗口中的提示;创建Cat类的对象,把引用赋值给Cat类型的变量tommy,使用它来访问Cat类继承或重写的成员,观察代码窗口中的提示;再将引用变量tommy的值赋给animal,在其后添加语句animal.printWeight();观察printWeight()方法的输出结果有无变化。
class Mammal{
public int weight = 100;
protected int height = 100;
int legs = 100;
private int tail = 100;
public void printWeight(){
System.out.println("The weight is:"+weight);
}
protected void printHeight(){
System.out.println("The height is:"+height);
}
void printLegs(){
System.out.println("The legs is:"+legs);
}
private printTail(){
System.out.println("The tail is:"+tail);
}
}
class Cat extends Mammal{
@oerride
public void printWeight(){
System.out.println("The weight of the cat is:"+weight);
}
}
class Test{
public static void main(String args[]) {
Mammal animal = new Mammal();
Cat tommy = new Cat();
}
}
变量类型和Test的其他操作需要你自己手动看看