相关疑难解决方法(0)

对于类变量,向上转换和向下转换有什么区别

对于类变量,向上铸造和向下铸造有什么区别?

例如,在下面的程序类中,Animal只包含一个方法但Dog类包含两个方法,那么我们如何将Dog变量转换为Animal变量.

如果完成了施法,那么我们如何使用Animal的变量调用Dog的另一种方法.

class Animal 
{ 
    public void callme()
    {
        System.out.println("In callme of Animal");
    }
}


class Dog extends Animal 
{ 
    public void callme()
    {
        System.out.println("In callme of Dog");
    }

    public void callme2()
    {
        System.out.println("In callme2 of Dog");
    }
}

public class UseAnimlas 
{
    public static void main (String [] args) 
    {
        Dog d = new Dog();      
        Animal a = (Animal)d;
        d.callme();
        a.callme();
        ((Dog) a).callme2();
    }
}
Run Code Online (Sandbox Code Playgroud)

java casting downcast upcasting class-variables

124
推荐指数
7
解决办法
28万
查看次数

标签 统计

casting ×1

class-variables ×1

downcast ×1

java ×1

upcasting ×1