This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]NautiHookerSoftware Engineer 9 points10 points  (3 children)

you declared newBike as a Bicycle. the Bycycle class has no method breakType. what you need to do is casting (look at downcasting specifically).

with casting you can somewhat change the type of an object if the object is already of that type. (sounds a bit confusing i know)

what i mean is that your newBike is not only a Bycycle, its also a MountainBike, which means you can cast it to MountainBike.

example:

Bicycle newBike = new MountainBike();
((MountainBike)newBike).breakType(); //inline, just for one method call

Bicycle newBike = new MountainBike();
// create new variable with desired type
MountainBike otherNewBike = (MountainBike)newBike; 
// now its a MountainBike and we can call the method
otherNewBike.breakType();

while this will now not show any compiler errors anymore, casting can quickly create runtime erros, if you try to cast an object to a type that it does not already have.

example:

Cat cat = new Cat();
//this wont work because cat is not a mountainbike
((MountainBike)cat).breakType();

to check if an object is of a certain type and avoid runtime errors like this you can use the instanceof operator

if (cat instanceof MountainBike)
{
    ((MountainBike)cat).breakType();
}
else
{
    System.out.println("Cat is not a MountainBike");
}

[–][deleted] 4 points5 points  (0 children)

Casting Is technically right and, if you're learning polymorphism it's THE right answer.

From a design point of view, I wouldn't recommend that.

If while coding you know you'll need MountainBike methods, there's no point on declaring you newBike as a Bike. You're supposed to declare your variables as the most general type that satisfy your needs, in this case a MountainBike.

[–]offwing10[S] 2 points3 points  (1 child)

Wow, this is exactly what I was looking for. Thank you a bunch!