Hey guys, sorry if this has been answered on this forum already. I searched around a bit and couldn't find the specifics of what I am confused about.
Basically I've created a small program to test my overall understanding of encapsulation, inheritance, and polymorphism. I'm using Planets in the solar system as the theme, basically making a superclass "Planet" that has subclasses "Mercury", "Venus", etc. Here is code for my parent class "Planet", and one subclass "Mercury". I'm using mass, temperature, and distance from the sun as the 3 variables that every planet inherits.
Parent class "Planet"
public class Planet { private double mass; private double temperature; private long distance; //Planet constructor public Planet(double size, double temp, long dist) { mass = size; temperature = temp; distance = dist; } //default constructor public Planet() { } //display method public void display() { } //get mass public double getMass() { return mass; } //set mass public void setMass(double size) { mass = size; } //get temp public double getTemp() { return temperature; } //set temp public void setTemp(double temp) { temperature = temp; } //get dist from sun public long getDistance() { return distance; } //set distance from sun public void setDistance(long dist) { distance = dist; } }
And the Mercury class...
public class Mercury extends Planet { public Mercury(double mass, double temperature, long distance) { setMass(mass); setTemp(temperature); setDistance(distance); } public void display() { System.out.println("Planet Mercury has a mass of " + getMass() + " Earths."); System.out.println("Its average temperature is " + getTemp() + " degrees Fahrenheit."); System.out.println("Its distance from the sun is " + getDistance() + " Kilometers."); } }
Finally here is the PlanetTest class which is the main method....
public class PlanetTest { public static void main(String[] args) { Planet mercury = new Mercury(0.55, 350, 57910000); mercury.display(); } }
Basically I understand how to inherit functionality from the Planet superclass, which in this case I am inheriting the getters and setters. I want to be able to also inherit a display method from the superclass, but I am unsure of how to go about it. Does each child class need a display method, or is my approach incorrect? I feel as though my understanding of polymorphism is lacking a bit.
Any help or tips are much welcome and appreciated!
Thanks for you time,
Todd