从 object 的角度来看,child 类 是否等同于他们的 racine class?

Are child Classes equivalent to their racine class from type of object perspective?

我创建了 3 个摘要 classes:

class文章:妈妈Class

public abstract class Article{
    //myPrivate Var Declarations
    public Article(long reference, String title, float price, int quantity){
        this.reference  =   reference;
        this.title      =   title;
        this.price      =   price;
        this.quantity   =   quantity;
    }
}

class Electromenager : child 文章

public abstract class Electromenager extends Article{
    //myVar declarations 
    public Electromenager(long reference, String title, float price, int quantity, int power, String model) {
        super(reference, title, price, quantity);
        this.power  = power;
        this.model  = model;
    }
}

Class Alimentaire:文章

的另一个child
public abstract class Alimentaire extends Article{
    private int expire;
    public Alimentaire(long reference, String title, float price, int quantity,int expire){
        super(reference, title, price, quantity);
        this.expire = expire;
    }
}

假设这些 class 必须是抽象的,所以基本上在主要 class 中,我不能直接实例化它们 objects 来这样做,所以我们需要这样做一些基本的扩展..:[=​​20=]

class TV extends Electromenager {
    public TV(long reference, String title, float price, int quantity, int power, String model){
        super(reference,title,price,quantity,power,model);
    }
}
class EnergyDrink extends alimentaire {
    public EnergyDrink(long reference, String title, float price, int quantity,int expire){
        super(reference,title,price,quantity,expire);
    }
}

所以我的困惑开始出现在这里!在 main() 中写这个时:

Article art         = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG");
EnergyDrink art2    = new EnergyDrink (155278 , "Eau Miniral" , 6 , 10, 2020);

令人惊讶的是我得到了零错误!!!!我不应该输入::

TV art          = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG");
//instead of
Article art     = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG");

为什么两种写法都是正确的? Java 编译器如何理解这一点?

你需要考虑行 Article art = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG");

分两个独立的步骤,

  1. 使用 new 运算符
  2. 创建 TV 类型的 Object
  3. 声明类型为 Article 的引用类型变量 art 并将在步骤#1 中创建的 TV 对象分配给它

您在第 1 步中调用了 TV 类型的有效构造函数,并且由于 ArticleTV 的父级,因此在第 2 步中赋值也是有效的。

Child classes 具有其基础 class.

的所有功能

Article art         = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG");

声明art作为文章object,这没有错。如果不强制转换,您将无法访问 TV-only 函数。 总之,新电视 object 已创建。如果你施放它:

TV tv         = (TV) art;

不会有任何问题,您可以访问所有电视功能。

更笼统地说,甚至

Object object = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG");

会起作用。