简体   繁体   中英

How do I pass a constructor to a constructor?

The question says "Add a constructor to the Point class that accepts another Point as a parameter and initializes the new Point to have the same (x, y) values. Use the keyword this in your solution."

public  class Point
{
  int x;
  int y;
  //enter your code here
}

What I have applied all the concepts I can think of and hit and trial method,but none of them worked. I mean how can I pass a constructor to a constructor! This is the best I came up with.

 public Point(Point)
 {
     this.x=x;
     this.y=y;
  }

But this generates an error. "< identifier> expected public Point(Point)"

Your constructor should be:

public Point(Point p) {
    this.x = p.x;
    this.y = p.y;
}

This way you assign p 's attributes to your class's attributes.
You did not include the identifier p .
Although if this is the only constructor of the class then the class is useless since it needs a preinstantiated object in order to instantiate a new one.

At least you need to give a constructor parameter variable a name:

public Point(Point p) {
 this.x = p.x;
 this.y = p.y;
}

You don't have to pass a constructor to constructor, just an instance is enough to copy it. Instance of the class has an access to all the private fields of the same class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM