-1

For example I have abstract class Shape, that gets the coordinates of the shape:

public abstract class Shape{
    private int x;
    private int y;

    public Shape(int x, int y){
        this.x=x;
        this.y=y
    }

    public abstract void onDraw();

}

Now I have the class Rect the extends from Shape:

public class Rect extends Shape{
    private int height;
    private int width;

    public Rect(int height, int width){
        this.height=height;
        this.width=width;
    }

    @Override
    public void onDraw(){
        //this method should get the width and height and the coordinates x and y, and will print the shape rect
    }
}

Now my question is: how can I get the coordinates x and y of the abstract class Shape from within Rect?

Riccardo T.
  • 8,907
  • 5
  • 38
  • 78
Omer
  • 307
  • 5
  • 17

3 Answers3

7

You can't get them as long as they are private. make them protected instead.

More information can be found here.

Community
  • 1
  • 1
exception1
  • 1,239
  • 8
  • 17
6

simply make some getters for them:

public abstract class shape{
    private int x;
    private int y;

    public shape(int x,int y){
        this.x=x;
        this.y=y
    }

    public abstract void onDraw();

    }

    public int getX() {
        return this. x;
    }

    public int getY() {
        return this. y;
    }

or make the attributes protected.

note that x and y will never be set if you create a rect because you are not calling the super constructor

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
0

You can't. The whole point of it being private is that you can't get at the variable. If the class hasn't given any way of finding it out, you can't get it.

Engineer2021
  • 3,288
  • 6
  • 29
  • 51