Auf Thema antworten

okey, ich versuchs mal so einfach wie es mir einfällt....


Stell dir vor, ein JLabel ist eine Pflanze, und dein ImageLabel ist ein Kaktus.


Dein ImageLabel (Kaktus) erbt von JLabel (Pflanze ) (Dein kaktus ist also im prinzip eine Pflanze)


Wenn du jetzt deine variable wie folgt initialisierst:


Pflanze lblImages = new Kaktus()


dann geht das supi, weil der Kaktus ja auch eine Pflanze ist, wenn ich also mit lblImages arbeite und davon ausgehe, das es eine "Pflanze" ist obwohl es eigentlich ein Kaktus ist ist das kein Problem.


Beispiel: Hey Pflanze, wie groß bist du? (Kaktus antwortet: ) 30cm


Das ist alles soweit ok, problem wirds aber, wenn wir das spiel umdrehen:


Hey Pflanze, wie lang sind deine Stackeln? (Apfelbaum extends Pflanze antwortet: hää?)



Dein Problem ist folgendes: Die Methode getImg() ist teil von ImageLabel (deinem kaktus), deine variable lblImages ist aber vom typ JLabel (Pflanze)


Der Programmcode kann also nicht wissen, das die Pflanze eigentlich ein Kaktus ist und deswegen seine Methoden (getStackel()) nicht aufrufen, weil Pflanzen normalerweise keine Stackeln haben sondern nur der Kaktus, dein Programm weis aber nicht das lblImages nen Kaktus ist.



Du kannst folgendes tun:

A) Ändere den Typ deiner Pflanze lblImages zu ImageLabel (Kaktus)

b) Da es ja eigentlich ein Kaktus ist, kannst du einen CAST machen (schmutzige variante)


Ein Cast bedeutet, das du dem compiler explizit sagst "Hey, ich weiss es besser als du, das ist nen KAKTUS!", problem ist dann nur, wenn es mal wirklich ein Apfelbaum ist, dann crashed dein programm



edit::


hier mal ein paar links dazu:

Polymorphie (Programmierung)

What is Type Casting in Java - Casting one Class to other class or interface Example



Oben