Invoking a superclass constructor in my subclass
I have a superclass called AstroObj, and two subclasses, Planet and Star.
Everything on my code works except the constructor that takes all parameters.
I want to inherit the name, galaxy, category and mass from my superclass but I'm getting an error that says they cannot be resolved. Can someone please tell me what is wrong here? (I didn't include the rest of my code cause everything else is fine, including the application program in the main method.)
AstroObj
Code :
public class AstroObj
{
private String name; //name assigned to object
private String galaxy; //name of galaxy which object belongs
private String category; //category associated with the object
private double mass; //mass of object
//default constructor, no parameters
public AstroObj()
{
name = "unknown";
galaxy = "unknown";
category = "unknown";
mass = 0.0;
}
//constructor with parameters
public AstroObj(String nameIn, String galaxyIn, String categoryIn, double massIn)
{
name = nameIn;
galaxy = galaxyIn;
category = categoryIn;
mass = massIn;
}
Planet
Code :
public class Planet extends AstroObj
{
private int numMoons; //additional instance variable
private double avgTemp; //additional instance variable
//subclass, default constructor
public Planet()
{
super();
numMoons = 0;
avgTemp = 0.0;
}
//constructor with all parameters
public Planet(String nName, String nGalaxy, String nCategory, double nMass, int moonsIn, double tempIn)
{
super(initName, initGalaxy, initCategory, initMass);
numMoons = moonsIn;
avgTemp = tempIn;
if(moonsIn < 0) //check for invalid number of moons
{
numMoons = 0;
}
}
Re: Invoking a superclass constructor in my subclass
What are initNAme, initGalaxy, initCategory, and initMass? When do you initialize them?
Re: Invoking a superclass constructor in my subclass
well they're supposed to be the variables from the superclass AstroObj, i just called em something different than what is gonna be passed from the main so i wouldn't get confused.
main
Code :
//first object with no parameters
AstroObj astro1 = new AstroObj();
System.out.println(astro1.toString());
//planet object
Planet planet1 = new Planet("Earth", "Milky Way", "Planet", 5.97E24, 1, 60.0);
System.out.println(planet1.toString());
Re: Invoking a superclass constructor in my subclass
Quote:
Originally Posted by
kari4848
well they're supposed to be the variables from the superclass AstroObj, i just called em something different than what is gonna be passed from the main so i wouldn't get confused.
Well, you can't do that. You have to declare and initialize a variable before you can use it.
Re: Invoking a superclass constructor in my subclass
Ahh, I fixed it and it works great now. Thank you for your help! :)
Re: Invoking a superclass constructor in my subclass
No problem. Glad you got it sorted.