문제

I want to first point out that I am very new to Java so go easy. :)

I have a method that randomly generates a name. I'm just wondering if it is better practice to call methods with return types directly like this:

String personName = People.nameGen();

or as I've recently learned, create 'get' methods to get the 'instance?' variables like this:

public String getName(){
return this.name;
}

then:

String personName = Person1.getName();

I've tried both and they seem to work identical, I can't seem to wrap my head around why you would use one way other another.

or even call the instance variables directly..?

name = People.name; or something like that?

All of these options would generate the output of a name of the person that I generated in that method.

EDIT, This is what I have:

import java.util.Random;
public class People {

int genderCode;
int age;
String gender;
String name;

public People(){
    genderCode = genderCode(); //I use genderCode for the nameGen method
}

public int genderCode(){
    Random randNum = new Random();      
    genderCode = randNum.nextInt(2);
    return genderCode;
}

public int age(){
    Random randNum = new Random();      
     age = 1+randNum.nextInt(80);
    return age;
}   

public String gender(){
    if (genderCode == 0 && age <=18) {
        gender = "girl";
    } else if (genderCode == 0 && age >18){
        gender = "woman";
    } else if (genderCode == 1 && age <=18){
        gender = "boy";
    } else if (genderCode == 1 && age >18){
        gender = "man";
    } 
    return gender;
}

public String nameGen() {
    String[] firstNameGirl = { "Lucy", "Marry", "Bonnie", "Clair" }; //More names will be added later
    String[] firstNameBoy = { "Bob", "Jacob", "William", "Nathan" };
    String[] lastName = { "Smith", "Brown", "Johnson" };

    Random randNum = new Random();

    if (genderCode == 0) {
        String girlName = firstNameGirl[randNum.nextInt(firstNameGirl.length)]+ " "+ lastName[randNum.nextInt(lastName.length)];
        name = girlName;
    } else if (genderCode == 1){
        String boyName = firstNameBoy[randNum.nextInt(firstNameBoy.length)]
                + " " + lastName[randNum.nextInt(lastName.length)];
        name = boyName;
    }
    return name;
}
}

Then for the main, I just want to make a new person at will.. eg:

System.out.println("You meet a " +age+ " year old " +gender+ " named " + name);

Thanks to all the quick answers! They were all uniquely informative!

도움이 되었습니까?

해결책

Your instance variables are generally private, which is why you would create a getter/setter to access them. Your getName() method is a public method that any class can call. Which one you use depends on how you want your class to function. If the purpose of the class is generate a random name, you would use Jigar's example.

If your getName() function is supposed to retrieve the name of a person (an instance variable), then you would use a getter.

다른 팁

I would leave standard accessor methods (getter/setter) for its default purpose to access fields, and create another class called

class PersonUtils{

    public static String getRandomName(){
      // code
    }
}

Use this:

private Person () 
{private String name;

private void setName(String name ) {
this.name=name;
}
private getName(){
this.name=name;
return name;
}

}

The question to ask yourself is what is the job or responsibility of the People class (or the Person1 class - you seem to have used different names) and how much external resource, coordination and time will it need? These questions should also lead you to examine: will your class need to preserve state of the name or anything else? In other words, is generating the name expensive? Will you only need the name once? Will you need to share one single name, or will you need different names for different users or threads or whatever?

For example, if your method creates a random name by simply iterating and a few calls to Math.random(), and you want a different name each time, this sounds suited to a static utility class:

public final NameUtils {
    private final NameUtils() {} // only allow access to static methods

    // 2 consecutive calls will give different results
    public static String generateName() {
        StringBuilder name = new StringBuilder();
        // do stuff to generate name
        return name.toString();
    }
}

Alternatively, if your name generation involves lookups and fetches to a database, a library of xml files and/or some external website or service (be it SOAP or REST or whatever) or even just parsing a flat file with a list of common names in it, then you need something more involved, but which involvement is hidden from the calling code.

public interface NameGenerator {
    // 2 consecutive calls should give same result for a given instance
    String getName();
    // Might take a while (30 seconds or more) consider wrapping in a thread and using a `Future`
    void generateName() throws NameGenerationException;
}

public class NameGeneratorImpl implements NameGenerator {
    private String name = null;
    public String getName() { return this.name; }
    public void generateName() {
        Resource resource = // for example database connection
        try {
            // this might even be broken down into multiple private methods
            // a. access resource
            StringBuilder nameBuilder = new StringBuilder();
            // b. get data from resource
            // c. use data in name formula
            this.name = nameBuilder.toString();
        } catch(ResourceException e) {
            throw new NameGenerationException(e);
        } finally {
             // free expensive resource
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top