Quote (carteblanche @ 15 Feb 2014 18:26)
i assume this is a homework assignment, in which case @bolded you misread your requirements. post your exact requirements, word for word.
in java, the methods you have available at runtime are based solely on your object type, the class whose constructor you invoked (eg: new Audi() or new Car()).
if you wanna be able to call the methods from the Audi class, then you must have an object of the Audi class or an object of a subclass of Audi. Since Car is neither, you can never call the methods from Audi.
Changing the reference type (eg: the type of the variable) only tells the compiler what is available. ex:
Car c = new Audi();
// Car is the reference type, so you can only call methods in Car, not methods in Audi
Audi a = (Audi)c;
// this is a valid cast; now you can call any methods of Audi
In java, you can not magically add new methods to an existing class at runtime as far as i'm aware. (possibly if you mess with custom class loading, but beyond the scope of any beginner's homework assignment). so if you create a Car object (eg: new Car()) then you can never call methods that exist in Audi
Quote (m0hawk @ 15 Feb 2014 18:28)
If it's not possible to do Car car = new Audi() it means that Audi does not extend Car, therefore the cast doesn't make any sense. If you really want to treat car as an Audi, you'll have to apply the Adapter pattern. However we can't show you how if you don't post the full code we're working on
Sorry i haven't replied earlier, figured i have to rework my entire program due to what you mentioned here. This is however not an assignment, i just figured it would be easier explaining my situation using the Car&Audi objects :P.
Quote (Minkomonster @ 16 Feb 2014 03:33)
Code
public abstract class Animal
{
public abstract void say();
}
public class Cow extends Animal
{
public void say()
{
System.out.println("Moo!");
}
}
public class Fish extends Animal
{
public void say()
{
System.out.println("Blub");
}
}
public class Fox extends Animal
{
public void say()
{
System.out.println("Ring-ding-ding-ding-dingeringeding! Gering-ding-ding-ding-dingeringeding! Gering-ding-ding-ding-dingeringeding!");
}
}
public class AnimalTest
{
public static void main(String[] args)
{
Animal animal;
//what does the cow say?
animal = new Cow();
animal.say();
//what does the fish say?
animal = new Fish();
animal.say();
//what does the fox say?
animal = new Fox();
animal.say();
}
}
This was actually exactly what i've been looking for. The issue is that you can only create animals as new objects of say fish, not typecast it if the fish has already been instantiated.
Car car = new Car();
car.setColor("red");
Audi audi = (Audi)car;
// This does not work

However ty everyone for the help, it's nice knowing that i didnt spend my time rewriting shitton of code for nothing :<