+ 1

Why does this code only work if i invoke extends and create the subclass in main?

I originally defined the subclass "racecars" before the main, but it gave me an error (something about static/non-static variables--an aspect of Java that I don't fully comprehend yet) when I tried to create a new "racecar" in main. Here is the working code: public class Vehicle { protected String tires, color; public Vehicle() { tires = "four"; color = "blue"; } public static void main(String[] args){ class racecar extends Vehicle{ racecar(){ color="red"; } } Vehicle ford = new Vehicle(); racecar vw =new racecar(); } } Thanks in advance for your help, I'm supposed to be teaching Java in the fall so I need a firm grasp of all concepts.

16th Jun 2017, 4:02 PM
Timothy Ryan
Timothy Ryan - avatar
4 odpowiedzi
+ 3
so as to use the color variable of vehicle class you need to first extend that class i.e. inherit from that class...
16th Jun 2017, 4:15 PM
cHiRaG GhOsH
cHiRaG GhOsH - avatar
+ 3
works perfectly with me see this https://code.sololearn.com/cHqFj2N4Ji2u/?ref=app
16th Jun 2017, 4:47 PM
cHiRaG GhOsH
cHiRaG GhOsH - avatar
+ 1
So, what is the difference between using "extends" before main, as opposed to using it in main. The way my code was written, it only worked if I created the subclass in main and I'm trying to figure out why.
16th Jun 2017, 4:38 PM
Timothy Ryan
Timothy Ryan - avatar
+ 1
Oh, now I see what my problem was. The first time I set it up I had "racecar extends vehicle..." inside of the vehicle class. So I just need to make sure that I declare a subclass outside of (ie. before, as in your example) the parent class. Thank you so much for your help and prompt replies!
16th Jun 2017, 5:10 PM
Timothy Ryan
Timothy Ryan - avatar