-2

So basically I have a superclass of a Geometric Figure that has private fields, say length and width. I have a subclass of a Rectangle that has a length and width in the constructor.

In the subclass, I must include a method to set the length and width of the Rectangle to the length and width of the private fields of the Geometric Figure. How do I do this?

Thanks

EDIT: For example:

public class GeometricFigure{
private double length;
private double width;
}

public class Rectangle extends GeometricFigure{
     public Rectangle(int length, int width){}
//set and get methods here to set the private fields to the variables in the parameter
}
noobforce
  • 77
  • 6

2 Answers2

0

You can create getter and setter methods in the superclass like:

public GeometricFigure(int length, int width)
{
     this.length = length;
     this.width = width;
}

public Rectangle(int length, int width)
{
    super(length, width);
}

Your 2 constructors could look like this.

brso05
  • 13,142
  • 2
  • 21
  • 40
0

You have a few options,

  1. Provide constructor in super class which accepts width and length. Subclass will use it
  2. Provide setter/getter method in super class which accepts width and length, just use it in the subclass

Otherwise you have no access to set private fields. (except reflection)

Orhan Obut
  • 8,756
  • 5
  • 32
  • 42