-1

By that I mean a baseclass, which was not itself initialised using an instance of the derived class. i.e. lets assume it is not an abstract class.

class GeomObj{
  Colour x;
}

class Triangle extends GeomObj{
  largestAngle y;
}

GeomObj u;

//now is the following allowed?Taking into account that u was not initialized using an instance of Triangle in the first place

Triangle v = (Triangle)u;
Marie Simm
  • 13
  • 1

2 Answers2

2

No because a GeomObj is not a triangle. But the inverse works:

Triangle u;
GeomObj v = (GeomObj)u;
JFPicard
  • 5,029
  • 3
  • 19
  • 43
  • 1
    It's like with dogs and pubs: each pub (subcalss) is a dog (superclass), but not each dog is a pub. =) – Turing85 Apr 13 '15 at 16:58
  • I was just wondering why it can't be converted like int to double when using typecast, where simply a new object is created with the additional parameters. and thanx for the answer :) – Marie Simm Apr 13 '15 at 18:15
0

Furthermore, you can say that every Triangle is GeomObj, but not every GeomObj is a Triangle. So the compiler won't allow you to do that.

Rafał P
  • 252
  • 1
  • 8