Results 1 to 4 of 4
Thread: Constructors?
- 01-27-2010, 07:47 AM #1
Member
- Join Date
- Jan 2010
- Posts
- 4
- Rep Power
- 0
Constructors?
I'm in the midst of my tutorial and am stuck at this qns.
Below is the code,
class UsePoint
{
public static void main(String[] args)
{
Point p=new Point();
p.print();
}
}
class Point
{
private int x;
private int y;
Point() (CONSTRUCTOR? WHAT THEY ACTUALLY DO)
{
this(0,0);
}
Point(int x,int y)
{
this.setPoint(x,y);
}
void setPoint(int x, int y)
{
this.setPoint(x,y);
}
void print()
{
System.out.println("Point: ");
System.out.println(this.x);
System.out.println(this.y);
}
}
Before attempting the qns, I need some help on the parts of the code I don't understand (in a different color and underlined).
Need help understanding them!Thanks!
- 01-27-2010, 08:14 AM #2
Member
- Join Date
- Dec 2009
- Posts
- 76
- Rep Power
- 0
please read this link. It was for me the best link. please read all pages of this link.
Object Initialization in Java
- 01-27-2010, 08:27 PM #3
Okay I think I can help you with this.
then you can make a scanner object that lets you input what ever you want for x and y. then you can use system.out to print the point.Java Code:public Point(int x, int y) { //sets private int x to int x in the constructor parameters. Then sets private int y to int y in the constructor parameters. So what ever you put in for x and y will be where the point is at. x=x; y=y;
I hope this helped. I'm not quite sure if it did.
-
Not quite. These statements in fact don't do anything:
Java thinks that you are trying to set a parameter = to itself, even if you have class fields named x, and y. The proper way to set class fields with the same name as method or constructor parameters is to use the "this" key word:Java Code:x = x; y = y;
Java Code:this.x = x; this.y = y;
Similar Threads
-
constructors?
By shroomiin in forum New To JavaReplies: 4Last Post: 10-13-2009, 02:14 PM -
Constructors
By new2java2009 in forum New To JavaReplies: 5Last Post: 08-18-2009, 06:46 AM -
Need some help with a task, constructors.
By JKM in forum New To JavaReplies: 1Last Post: 02-01-2009, 10:09 PM -
Help with constructors
By Minime in forum New To JavaReplies: 3Last Post: 04-09-2008, 07:59 AM -
constructors
By khamuruddeen in forum New To JavaReplies: 2Last Post: 12-01-2007, 03:15 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks