public class Square {
public double height;
public double width;
public double surfaceArea;
Square(double height, double width) {
this.height = height;
this.width = width;
}
public void setHeight(double height) {
this.height = height;
}
public double getHeight() {
return this.height;
}
public void setWidth(double width) {
this.width = width;
}
public double getWidth() {
return this.width;
}
public double computeSurfaceArea() {
this.surfaceArea = this.height * this.width;
return this.surfaceArea;
}
public double getSurfaceArea() {
return this.surfaceArea;
}
}
public class Cube extends Square {
private int depth = 6;
Cube(double height, double width) {
super(height, width);
}
public double computeSurfaceArea() {
super.surfaceArea = (super.height * super.width) * depth;
return super.surfaceArea;
}
}
import java.util.Scanner;
public class DemoSquare {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Square square;
Cube cube;
double doubleValue1, doubleValue2;
System.out.print("Enter value for height: \n>> ");
doubleValue1 = input.nextDouble();
System.out.print("Enter value for width: \n>> ");
doubleValue2 = input.nextDouble();
square = new Square(doubleValue1, doubleValue2);
cube = new Cube(doubleValue1, doubleValue2);
System.out.println("\n<Results>\n");
System.out.println("Surface area of <Square Class>: " + square.computeSurfaceArea());
System.out.println("Surface area of <Cube Class>: " + cube.computeSurfaceArea());
}
}
Is it okay if I make my class fields(Parent class) to public rather than private? It's because im using the concept of inheritance right here. Or should I use the getters/setters method in the parent class.
via Sean
No comments:
Post a Comment