课后作业4.3

发布时间 2023-10-13 10:32:27作者: 千恒

一、怎样判断对象是否可以转换?

可以使用instanceof运算符判断一个对象是否可以转换为指定的类型: Object obj="Hello"; if(obj instanceof String) System.out.println("obj对象可以被转换为字符串");

public class TestInstanceof
{
    public static void main(String[] args)
    {
        //声明hello时使用Object类,则hello的编译类型是Object,Object是所有类的父类
        //但hello变量的实际类型是String
        Object hello = "Hello";
        //String是Object类的子类,所以返回true。
        System.out.println("字符串是否是Object类的实例:" + (hello instanceof Object));
        //返回true。
        System.out.println("字符串是否是String类的实例:" + (hello instanceof String));
        //返回false。
        System.out.println("字符串是否是Math类的实例:" + (hello instanceof Math));
        //String实现了Comparable接口,所以返回true。
        System.out.println("字符串是否是Comparable接口的实例:" + (hello instanceof Comparable));
        String a = "Hello";
        //String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过
        //System.out.println("字符串是否是Math类的实例:" + (a instanceof Math));
    }
}

结果:

字符串是否是Object类的实例:true
字符串是否是String类的实例:true
字符串是否是Math类的实例:false
字符串是否是Comparable接口的实例:true

二、类型转换”知识点考核-2

现在有三个类: class Mammal{} class Dog extends Mammal {} class Cat extends Mammal{}

针对每个类定义三个变量并进行初始化 Mammal m=null ; Dog d=new Dog(); Cat c=new Cat();

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=m和d=c会报错

三、在实践中理解把握复杂的知识-1

子类和父类定义了一模一样的字段和方法

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();

    }
}

class Parent{
    public int myValue=100;
    public void printValue() {
        System.out.println("Parent.printValue(),myValue="+myValue);
    }
}
class Child extends Parent{
    public int myValue=200;
    public void printValue() {
        System.out.println("Child.printValue(),myValue="+myValue);
    }
}

结果:

Parent.printValue(),myValue=100
Child.printValue(),myValue=200
Child.printValue(),myValue=200
Child.printValue(),myValue=200
Child.printValue(),myValue=201

总结:

当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。 这个特性实际上就是面向对象“多态”特性的具体表现。

如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它。 如果子类被当作父类使用,则通过子类访问的字段是父类的! 牢记:在实际开发中,要避免在子类中定义与父类同名 的字段。不要自找麻烦!——但考试除外,考试 中出这种题还是可以的。