Search code examples
javainheritancesuperclasssuper

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


I've created 3 abstract classes:

class Article : mother 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 : a child of 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;
    }
}

Class Alimentaire: another child of 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;
    }
}

Let's just suppose that these classes must be abstract, so basically in the main class, I can't instantiate directly their objects to do so we need to do some basic extends..:

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);
    }
}

So here where my confusion start to occur ! when writing this in the main():

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

Surprisingly I'm getting zero error !!!! shouldn't I type: :

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

Why both writing are correct? And how does the Java compiler understand this?


Solution

  • Child classes have all the functionality of their base class.

    By saying

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

    you declare art as an Article object, which is not wrong. You won't be able to access TV-only functions without casting. Anyway an new TV object is created. If you cast it:

    TV tv         = (TV) art;
    

    There won't be any problem and you can access all the TV functions.

    To be more general, even

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

    would work.