我创建了 3 个抽象类:
类(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;
}
}
Electromenager 类:Article 的子级
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;
}
}
Alimentaire 类:Article 的另一个子级
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 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");
你声明 art
作为一个Article对象,这并没有错。如果不进行转换,您将无法访问仅限电视的功能。
不管怎样,一个新的 TV 对象被创建了。如果你转换它:
TV tv = (TV) art;
不会有任何问题,您可以访问所有电视功能。
更一般地说,甚至
Object object = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG");
可以。
关于java - 从对象类型的角度来看,子类是否等同于它们的 racine 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34917362/