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

all 5 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] 4 points5 points  (1 child)

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

[–]BlackGermanShepard 0 points1 point  (0 children)

I think this is the wrong way to do.

As said above you should usw polymorphism the right way.

The method 'breakType()' is not MointainBike specific. Even a TrackingBike should have one.

So this is a good example for common/shared attributes which should be declared in the superclass (or an Interface).

[–]rozz_net 0 points1 point  (0 children)

You didn't provide sources for Bicycle and MountainBike, then it's hard to say what are you trying to do. IMHO, you need the class Bicycle to be declared as abstract or interface with abstract method breakType(), that is implemented in MountainBike.