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


well know question not clear. bare me minute.

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

so, let's suppose these classes must abstract, in main class, can't instantiate directly objects need 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 confusion start occur ! when writing in 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 0 error !!!! shouldn't 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 correct ? , how java compiler understand ? !

child classes have functionality of base class.

by saying

article art         = new tv (145278, "oled tv", 1000 , 1 ,220, "lg"); 

you declare art article object, not wrong. won't able access tv-only functions without casting. anyway new tv object created. if cast it:

tv tv         = (tv) art; 

there won't problem , can access tv functions.

to more general, even

object object = new tv (145278, "oled tv", 1000 , 1 ,220, "lg"); 

would work.


Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -