Results 1 to 2 of 2
- 04-01-2008, 08:52 PM #1
Member
- Join Date
- Jan 2008
- Posts
- 5
- Rep Power
- 0
Inheritance, methods, and toString...
In the above code, LightTruck/Car/Etc extends Vehicle.Java Code:Vehicle [ ] acme = new Vehicle [5]; acme[0] = new LightTruck(111, "Elmer Fudd", "GM", 500); acme[1] = new Car(222, "Wile E Coyote", "Ferrari", 2, 10); acme[2] = new Passenger(333, "Foghorn Leghorn", "Toyota", 5); acme[3] = new Commercial(444, "Daffy Duck", "Mack", 42000); acme[4] = new Vehicle(555, "The Roadrunner", "Honda"); for(int i = 0; i < acme.length; i++) { System.out.println(acme[i].toString() + "\n"); } acme[0].changeCapacity(250); //ERRORS HERE
All the classes have their own toString method which print different things.
LightTruck has a method called changeCapacity.
The loop works and all the different toString methods return different values according to how its defined in the subclass (including private instance variables from the subclass).
But why does changeCapacity not work and errors? The error log seems to suggest that it is because the compiler checks the Vehicle class for the changeCapacity method, but if thats true, then how come toString works? Wouldn't toString() simply return what is only in the Vehicle method?
- 04-01-2008, 10:12 PM #2
The object located at acme[0] is a reference to a LightTruck object, but you are actually calling changeCapacity(int) on a Vehicle object. Where is changeCapacity(int) defined? If it's not in the Vehicle class, you may want to put it there and try again.
To answer your question about toString(), think of it as a universally assigned method to all objects/classes. Every object gets a specific set of methods defined here. From that link, you can see that toString() is defined there. If you've defined toString() methods in your Vehicle subclasses, then you've essentially overridden definitions higher up the hierarchy.Last edited by CaptainMorgan; 04-01-2008 at 10:15 PM.
Vote for the new slogan to our beloved Java Forums! (closes on September 4, 2008)
Want to voice your opinion on your IDE/Editor of choice? Vote now!
Got a little Capt'n in you? (drink responsibly)
Similar Threads
-
toString method
By apfroggy0408 in forum New To JavaReplies: 6Last Post: 01-31-2008, 04:08 AM -
Inheritance
By mew in forum New To JavaReplies: 1Last Post: 12-07-2007, 06:08 PM -
Arrays.toString
By Java Tip in forum Java TipReplies: 0Last Post: 12-01-2007, 09:35 PM -
Can i just use toString?
By cachi in forum New To JavaReplies: 1Last Post: 07-31-2007, 08:32 PM -
Inheritance in GUI
By Marty in forum SWT / JFaceReplies: 2Last Post: 05-11-2007, 12:54 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks