10.9日课后作业

发布时间 2023-10-15 22:52:24作者: 芊羽鱼
class Mammal{}
class Dog extends Mammal {}
class Cat extends Mammal{}

public class TestCast
{
public static void main(String[] args)
{
Mammal m;
Dog d=new Dog();
Cat c=new Cat();
m=d;
//d=m;
d=(Dog)m;
//d=c;
//c=(Cat)m;

}
}
将以上代码中的“d=(Dog)m;”替换掉分别出现以下问题:
c=(Cat)m;

 

d=c;p

 

d=m;

第一个在运行时出现错误,后两个在编译时出现错误。
public class ParentChildTest {
public static void main(String[] args) {
Parent parent=new Parent();
parent.printValue();
Child child=new Child();
child.printValue();

parent=child;
parent.printValue();

parent.myValue++;
parent.printValue();

((Child)parent).myValue++;
parent.printValue();

}
}
  1. 程序的运行结果为: 1 2 2 3 4

  2. 输出的解释如下:

    • 第一个输出是父类Parent的printValue()方法的结果,输出为1。
    • 第二个输出是子类Child的printValue()方法的结果,输出为2。
    • 第三个输出是通过将子类Child赋值给父类Parent,然后调用父类的printValue()方法,输出为2。这是因为子类对象被赋值给父类引用,但是调用的是子类的方法。
    • 第四个输出是通过父类引用修改父类的实例变量myValue,然后调用父类的printValue()方法,输出为3。
    • 第五个输出是通过将父类引用强制转换为子类Child,然后通过子类的引用修改子类的实例变量myValue,再调用父类的printValue()方法,输出为4。
  3. 从这些运行结果中,可以总结出Java的以下语法特性:

    • 多态性:子类对象可以赋值给父类引用,通过父类引用调用子类的方法。
    • 方法重写:子类可以重写父类的方法,调用同名方法时会根据实际对象的类型调用相应的方法。
    • 强制类型转换:可以将父类引用强制转换为子类引用,以便访问子类特有的属性和方法。但是需要注意,如果转换的引用不是子类的实例,会抛出ClassCastException异常。
    • 实例变量的访问:父类的实例变量可以被子类继承和修改,但是通过父类引用调用实例变量时,调用的是父类的实例变量。