有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有不同参数类型的java调用方法

我试图从第一本Java书的开头理解继承。在第193页,我把一切都搞定了,我试图用一个不同的参数调用一个方法(重载方法),但主类调用从超类继承的方法。如何调用以下方法

boolean frighten(byte b) {
    System.out.println("a bite?");
    return true;
}

我试图声明一个字节,但没用。 谢谢大家,以下是代码:

public class MonsterT {
    public static void main(String[] args) {
        Monster[] ma = new Monster[3];
        ma[0] = new Vampire();
        ma[1] = new Dragon();
        ma[2] = new Monster();
        for (int x=0; x < 3; x++) {
            ma[x].frighten(x);
        }

        byte y = 2;

        ma[0].frighten(y);
    }
}

class Monster {
    boolean frighten(int z) {
        System.out.println("arrrgh");
        return true;
    }
}

class Vampire extends Monster {
    boolean frighten(byte b) {
        System.out.println("a bite?");
        return true;
    }


class Dragon extends Monster {
    boolean frighten(int degree) {
        System.out.println("breath fire");
        return true;
    }

输出是:arrrgh breath fire arrrgh arrrgh


共 (2) 个答案

  1. # 1 楼答案

    这里的重点是重载和重写之间的区别——有关更多信息,请参见this answer

    因此,您的类树如下所示:

     Monster
    |       |
    Vamire  Dragon
    

    这意味着

    frighten(int z)
    

    方法通过对所有三个类的继承可用,并且可以重载(=相同的类型-就像在Dragon类中一样)

    boolean frighten(byte b) 
    

    是一个重写(不是同一类型的参数),因此可以调用

    frighten(byte) 
       and 
    frighten(int) 
    

    在你的吸血鬼身上

    另一个发挥作用的方面是object type casting

    因此,在最后,你的所有对象都是“怪物阵列”中的怪物“ma”-并且将被视为怪物

    这部电影将被演员们改成吸血鬼,他们在电影的答案中展示了科学的方法

    如果没有强制转换,字节将自动类型转换为int

  2. # 2 楼答案

    您可以通过将ma[0]转换为Vampire:((Vampire)(ma[0])).frighten(y);来实现这一点

    为什么它目前不起作用

    对于类和方法的当前结构,您无法做到这一点,因为Method Invocation Conversion是在使用byte参数调用Vampire对象上的frighten()时应用的:

    Method invocation contexts allow the use of one of the following:

    • an identity conversion (§5.1.1)

    • a widening primitive conversion (§5.1.2)

    • a widening reference conversion (§5.1.5)

    • a boxing conversion (§5.1.7) optionally followed by widening reference conversion

    • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

    具体来说,在你的情况下发生的是widening primitive conversion

    • byte to short, int, long, float, or double

    (在你的例子中:从byteint