【问题标题】:What does the compiler do when I extend class from user defined package?当我从用户定义的包中扩展类时,编译器会做什么?
【发布时间】:2020-09-20 23:23:23
【问题描述】:

我有一个名为 Drinks 的用户定义包,
其中有几个类

Drinks
    Water
        Cocoa (extends Water)
        Coffee (extends Water)
    CalculateDrinks

编译包后,我在默认包中创建了一个名为Cappuccino的类,扩展了Coffee,其中包含这些类。

Default
    Cappuccino
    TestPackage


在 CalculateDrinks 中,它有一个名为 calculatePrice() 的方法,它计算每个饮料的 getPrice() 的总和,包括 Cappuccino 类(它也有 getPrice 方法)。

请问,CalculateDrinks 类的calculatePrice() 方法如何知道Cappuccino 类的getPrice() 方法?
任何帮助,将不胜感激。如果您想查看源代码,请告诉我。

编辑: 添加了一些重要的代码部分

TestPackage.java

public class TestPackage{
    public void static main(String[] args){
        Coffee coffee = new Coffee(150);    //that is the price
        Cappuccino cap = new Cappuccino("snowman");

        Drinks drinks = {coffee, cap};
        CalculateDrinks cal = new CalculateDrinks(drinks);
        System.out.println("The total price of all drinks is " + cal.getTotalPrice()); //it should return 350
    }
}

CalculateDrinks.java

public class CalculateDrinks{
    private int totalPrice;
    private Drinks drinks[];

    CalculateDrinks(Drinks drinks[]){
        this.drinks = drinks;
        calculatePrice();
    }

    public void calculatePrice(){
        for (Drinks drink in drinks){
            totalPrice += drink.getPrice();
        }
    }  

    public int getTotalPrice(){
        return totalPrice;
    }  
}

Cappuccino.java

public class Cappuccino extends Coffee{
    private String pattern;
    Cappuccino(String pattern){
        this.pattern = pattern;
    }
    public int getPrice(){
        return super.getPrice() + 50;
    }
}

【问题讨论】:

  • 您能提供一个minimal reproducible example 来说明吗?
  • 你到底是什么意思?它怎么知道Cappuccino?除非TestDrinks 提到它,或者它把它作为参数或类似的东西传入它不会知道Cappuccino。你能告诉我们TestDrinks类在你的例子中是什么样子的吗?
  • @FredLarson 我已经添加了源代码,你能帮忙吗?

标签: java class oop package extends


【解决方案1】:

因为在calculatePrice() 中,它为每个饮料对象分别调用getPrice() 方法。

public void calculatePrice(){
    for (Drinks drink in drinks){
        totalPrice += drink.getPrice();
    }
} 

在上面for循环的第一步;它调用 coffe.getPrice() 因为饮料数组中的第一个饮料是一个咖啡对象。
第二步;它调用 getPrice()of 卡布奇诺对象 cap.getPrice().
您应该知道getPrice() 方法被每个子类覆盖,并且每个对象都在调用自己的getPrice() 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2010-10-27
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多