Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Suppose that you need a FullName class, which will contain a person's first name and last name.?

There are two different ways of implementing this.

A. The public variable version:

class FullName

{

public String first;

public String last;

}

B. The bean-style accessor version:

class FullName

{

private String first;

private String last;

public String getFirst() { return first; }

public void setFirst(String s) { first = s; }

public String getLast() { return last; }

public void setLast(String s) { last = s; }

}

Questions:

1. What are the benefits of using the public variable version?

2. What are the benefits of using the bean-style accessor version?

3. Add a constructor to your preferred version, that takes two String parameters and initializes first and last.

1 Answer

Relevance
  • 1 decade ago
    Favorite Answer

    Benefits of using the public variable version is that you don't need separate methods to get or set the first and last names from the caller. All you need is the dot.accessor

    so for example in your main:

    //create an object of the FullName class

    FullName test = new FullName();

    test.first = "whatever";

    test.last = "goes";

    System.out.println("first name is " + test.first);

    System.out.println("last name is " + test.last);

    Note how I never even had to call a method to set or get the names. However, this is generally bad. This defeats the purpose of encapsulation. We don't want the caller to change what inside our classes so easily without making them at least work for it. In larger programs, many errors will abound if you allow someone direct access to your variables.

    Thus always use the bean-style version and make your instance variables private. Encapsulation is the key word here. That's why you see a bunch of methods that have get or set. because if you tried to just use the dot accessor again, compiler will say "hold up buddy. You don't have the authority. Got to file the correct paperwork and go through the correct channels"

Still have questions? Get your answers by asking now.