Reputation: 365
I'm working with inheritance and polymorphism. I'm getting only this output instead of displaying the required points.
But printing points alone works properly. Printing lines creates problem.
Output: line joining null null
package serial;
import java.io.*;
class Point
{
private int x,y;
Point(int x,int y)
{
this.x = x;
this.y = y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
void setX(int x)
{
this.x = x;
}
void setY(int y)
{
this.y = y;
}
public String toString()
{
//String s = "Points joining line are ("+p1.getX()+","+p1.getY()+") and ("+p2.getX()+","+p2.getY()+")";
return "(" + x + "," + y + ")";
}
}
class Line
{
private Point p1, p2;
Line()
{
}
Line(Point p1, Point p2)
{
p1 = new Point(2,2);
p2 = new Point(3,3);
}
void setP1(Point p1)
{
p1.setX(2);
p1.setY(2);
}
Point getP1()
{
return p1;
}
void setP2(Point p2)
{
p2.setX(3);
p2.setY(3);
}
Point getP2()
{
return p2;
}
public String toString()
{
String str;
str = "line joining "+this.p1+" "+this.p2+"";
return str;
}
}
public class chumma {
public static void main(String args[])
{
Point p1 = new Point(2,2);
Point p2 = new Point(3,3);
Line l1 = new Line(p1,p2);
//l1.setP1(p1);
//l1.setP2(p2);
System.out.println(l1);
}
}
Upvotes: 0
Views: 55
Reputation: 17595
Your consturctor should look like this:
Line(Point p1, Point p2)
{
this.p1 = p1;
this.p2 = p2;
}
The mistake is that you are not assigning the member variables but the parameter which are hiding your member variables.
Use the this keyword to explicitly address the members of a class.
Upvotes: 0
Reputation: 178263
Your constructor reassigns the local references p1
and p2
instead of assigning the instance variables. Because the instance variables are not assigned, Java gives them a default value of null
.
Add this.
to refer to the instance variables.
Line(Point p1, Point p2)
{
this.p1 = p1;
this.p2 = p2;
}
You'll also want to assign something to those variables in your no-arg constructor.
Upvotes: 5