Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Björn Norén
9,569 PointsQuestion about oop & polymorphism
Hi, I'm trying to understand the best way to modify variables in a superclass when using multiple subclasses. For a example I created a class named Rectangle with a height and width:
abstract public class Rectangle {
private int height = 10;
private int width = 20;
public int getHeight(){
return height;
}
public void setHeight(int x){
height = x;
}
public int getWidth(){
return width;
}
abstract void printResult();
}
and two classes: Area which calcs area and Circuit wich calcs the Circuit
public class Area extends Rectangle {
public int calcArea(){
int height = getHeight();
int width = getWidth();
return height * width;
}
public void printResult(){
System.out.println("Area: " + calcArea());
}
}
public class Circuit extends Rectangle {
public int calcCircuit(){
int height = getHeight();
int width = getWidth();
return height * 2 + width * 2;
}
public void printResult(){
System.out.println("Circuit: " + calcCircuit());
}
}
and then I use a class for the output
public class RectangleOutput {
public static void main(String[] args) {
Rectangle area = new Area();
Rectangle circuit = new Circuit();
area.printResult();
circuit.printResult();
area.setHeight(30); //modifying height
area.printResult();
circuit.printResult();
/* Output:
* Area: 200
* Circuit: 60
* Area: 600
* Circuit: 60
*/
}
}
My problem now is that I don't know the best way to modify the variables in the superclass. When changing the height with the area-object it won't work on the circuit-object. Could someone please help me or give some tips on the best oop practise? Thanks!
1 Answer
james south
Front End Web Development Techdegree Graduate 33,271 Pointsi am new to java but i think you need some adjustments here. area and circuit should be methods called on rectangle objects, not objects themselves. a subclass of rectangle inheriting from the rectangle class would be something like square - a rectangle with 4 equal sides. a square subclass would then inherit the rectangle methods area and circuit. you seem to be missing a setWidth method, and you are not using the "this" keyword in your setters. in your main, you would then create a new rectangle object, be able to set and get width and height, and thus calculate and return area and circuit, and any of those could be printed to the console.