Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

please say what is wrong in code and how it will be corrected in class definitions

+5 votes
asked May 23, 2021 by Jahanvi Giriya (240 points)

class Point

{ private int x, y;

public Point (int x, int y)

{this.x = x; this.y = y;}

public int getX ( ) { return x; }

public int getY ( ) { return y; }

}

class ScaledPoint extends Point

{ private int c;

public ScaledPoint (int x, int y, int c)

{ this.x = x; this.y = y; this.c = c;}

public void getC ( ) { return c; }

}

2 Answers

0 votes
answered May 23, 2021 by Ravi Jaiswal (140 points)
1. Firstly we can't access the private data variable of parent class in chlid class.

2. While assign the values of variable of parent class use super()

Corrected Code below:

class Point

{
    public int x, y;

    public Point (int x, int y)
    {
        this.x = x;
        this.y = y;
    
    }
    
    public int getX ( ) { return x; }
    
    public int getY ( ) { return y; }

}
 class ScaledPoint extends Point

{
    private int c;

    public ScaledPoint (int x, int y, int c)
    {
        super(x,y);
        this.c = c;
        
    }
    
    public int getC ( ) { return c; }

}
+1 vote
answered May 24, 2021 by Peter Minarik (53,530 points)
edited Jun 4, 2021 by Peter Minarik

There were various problems with your code:

  • In Java the this pointer cannot be used in the constructor to access members. Since it cannot be used, you need to have different name for the arguments and the member variables. (I used the _ to prefix member variables.)
  • To set members in the base class, you better call the constructor of the base class from the constructor of the derived class. For this use the super() to invoke the base constructor.
  • Your getC() method had the wrong (void) return type. It should be int.
  • You need a main() method in your code

Here's the fixed code:

class Point
{
    private int _x, _y;

    public Point(int x, int y)
    {
        _x = x;
        _y = y;
    }

    public int getX() { return _x; }
    public int getY() { return _y; }
}

class ScaledPoint extends Point
{
    private int _c;

    public ScaledPoint(int x, int y, int c)
    {
        super(x, y);
        _c = c;
    }

    public int getC() { return _c; }
}

public class Main
{
    public static void main(String[] args)
    {
        ScaledPoint scaledPoint = new ScaledPoint(1, 2, 3);
    }
}
commented Jun 2, 2021 by AntonyGN (120 points)
very prestigious
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...