user user - 3 months ago 32
Java Question

Code clarification : DataModel model = new FileDataModel (new File("intro.csv"));

I'm confused by this java code, most likely due to my lack of object oriented programming skills.

DataModel model = new FileDataModel (new File("intro.csv"));

How is DataModel related to FileDataModel. Is this a 'isa' relationship? where FileDataModel isa DataModel, and if so, in general the parent class can equate to any subclass? Also can a object equate to another class where there is no relationship at all in terms of parent/subclass?


For your first question, yes.

FileDataModel is a DataModel and so one can give a DataModel reference a FileDataModel object... this is called upcasting, and is a core principle of OOP.

As for your second question, no. upcasting only works when the reference is a parent of the object created.

Number n = new Integer(1);// Integer is of type Number
String s = new Integer(5);// Integer is unrelated to String

In the example, I create an integer n but the reference is of type Number. That works because Integer extends (is a child of) Number. However, the second line won't compile. This is because String and Integer are not related to one another (neither is a parent of the other).