• Post Reply Bookmark Topic Watch Topic
  • New Topic

help with this code// constractors  RSS feed

 
vuthlarhi donald
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Person {

private String name;
private String surname;
private String address;
private String username;
private String email;
private int password;

public Person() // I want to initialz this to defaults without having to retype everything...I can use the this keyword, just don't know how
{

}
public Person() // this one initialz these values that I wil get from the main method, even if the user doesn't supply all the arguments, as long as more than one argument is supplied
{

}
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your no-argument constructor is not going to be very useful. You do realise that the fields are already initialised to default values; 0 for the int, and null for all the objects (Strings).
You don't need to use the keyword this yet. All you have to do is to set values for each of the fields in the constructor.
You will of course end up with a lot of people who all have the same name email and password!

A constructor with one argument is not a lot better. You can only initialise those fields which have information passed to them. You can't initialise name and expect your constructor to pick up an email address or a password from anywhere. So, if you have a one-argument constructor you can set whichever field that value applies to.

There is an example of a constructor here, in the Java Tutorial. Note that the names of the parameters are slightly different from the names of the fields, so you don't need to write this.
You can pass all the arguments as command-line arguments to the main method, but it will make for a long invocation. You could also have some sort of code in your constructor which asks the user to enter the other values. Maybe like this:-I don't think your second request is feasible.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the PM. It would have been better to post some of that code on the forum, so everybody can see your solution.

As for the toString() method, you might have something like thisThat is one of several possible ways to organise a toString method. I haven't looked at the rest of the code in detail, but it looks OK just on a 3-second glance.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!