加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么向上转换一个不改变重写方法的类?

发布时间:2020-12-15 04:31:24 所属栏目:Java 来源:网络整理
导读:参见英文答案 Overriding member variables in Java????????????????????????????????????10个 ???????????? Polymorphism with instance variables ????????????????????????????????????2个 我有一个继承自BritishPerson类的子类ScottishPerson. class Bri
参见英文答案 > Overriding member variables in Java????????????????????????????????????10个
>???????????? Polymorphism with instance variables ????????????????????????????????????2个
我有一个继承自BritishPerson类的子类ScottishPerson.

class BritishPerson {
    public String name = "A british name";

    public void salute() {
        System.out.println("Good Morning!");
    }
}

class ScottishPerson extends BritishPerson {
    public String name = "A scottish name "; //Variable overriding
    public String clanName = "MacDonald";

    public void salute() //Method overriding
    {
        System.out.println("Madainn Mhath!");
    }

    public void warcry() {
        System.out.println("Alba Gu Brath!");
    }
}

class Driver {

    public static void main(String[] args) {
        ScottishPerson scottishPerson = new ScottishPerson(); //Created as a subclass,can always be upcasted.
        BritishPerson britishPerson = new BritishPerson(); //Created as the superclass,throws an error when downcasted.
        BritishPerson britishPersonUpcasted =
                new ScottishPerson(); //Created as the subclass but automatically upcasted,can be downcasted again.

        //Checking the methods and parameters of scottishPerson
        scottishPerson.salute();
        scottishPerson.warcry();
        System.out.println(scottishPerson.name);
        System.out.println(scottishPerson.clanName);

        //Checking the methods and parameters of britishPerson
        britishPerson.salute();
        System.out.println(britishPerson.name);

        //Checking the methods and parameters of britishPersonUpcasted
        britishPersonUpcasted.salute();
        System.out.println(britishPersonUpcasted.name);
    }
}

运行代码,这是输出.

Madainn Mhath!
Alba Gu Brath!
A scottish name 
MacDonald
Good Morning!
A british name
Madainn Mhath!
A british name

这就是混乱所在.将ScottishPerson上传到BritishPerson将变量名称更改为超级类别中定义的变量名称.仅丢弃子类中存在的方法和变量,例如warcry()和clanName.但是,在upcasted类上调用方法salute()仍然会返回基于子类实现的字符串.

是因为当我创建对象britishPerson时我只初始化BritishPerson类,当我创建对象britishPersonUpcasted时,我创建了BritishPerson类和ScottishPerson类,导致了salute()方法的永久覆盖?

解决方法

请查看此问题,以便更好地理解上传和下传:

What is the difference between up-casting and down-casting with respect to class variable

我也做了一个看待上传行为的例子:

abstract class Animal 
{ 
    public void saySomething()
    {
        System.out.println("Some Animal sound");
    }

    public abstract void getTheBall();
}

class Horse extends Animal
{ 
    public void saySomething()
    {
        System.out.println("Neigh Neigh");
    }

    public void getTheBall()
    {
        System.out.println("I won't,Try a dog,I am a Horse!");
    }
}

class Dog extends Animal 
{ 
    public void saySomething()
    {
        System.out.println("woof woof,waon waon");
    }

    public void getTheBall()
    {
        System.out.println("huf huf,here it is!");
    }
}

public class Main 
{
    public static void main (String [] args) 
    {
        Dog dog = new Dog(); 
        Horse horse = new Horse();
        Animal animal = dog;
        Animal horseAnimal = new Horse();

        //upcasting
        Dog upcastedAnimal = upcastToDog(animal);
        dog.saySomething();
        dog.getTheBall();

        upcastedAnimal.saySomething();
        upcastedAnimal.getTheBall();

        horse.saySomething();
        horse.getTheBall();

        try {
            Dog upcastedDog = upcastToDog(horseAnimal);
        } catch (Exception ex){
            System.out.println(ex.getClass().getSimpleName() + ": Obviously a horse is not a dog!");
        }
    }

    public static Dog upcastToDog(Animal animal){
        return (Dog) animal;
    }
}

输出:

woof woof,waon waon
huf huf,here it is!
woof woof,here it is!
Neigh Neigh
I won't,I am a Horse!
ClassCastException: Obviously a horse is not a dog!

首先,如果尝试转换不兼容的类型,java将抛出异常.

在可以进行强制转换的情况下,将始终从实际实例调用overriden方法.在您的情况下,实例是ScottishPerson,因此即使您在BritishPerson中持有其引用,也会在ScottishPerson上调用方法.

你可以在这里运行这个例子https://repl.it/B83f/3

在JLS中,这里涵盖了“Narrowing Reference Conversion”,正如他的名字所暗示的那样,只有参考被缩小或扩大(或上升或下调)而不是实例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读