Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have my utmost respect to my professor that he knows everything about Java. But I am having difficulty understanding his explanation about constructors and set/get methods. What are they being used for? If someone can explain a little more hopefully I can get the AHA moment.

share|improve this question
Constructors and get/set methods exist in other programming languages, not just Java. – Bernard Mar 21 '12 at 2:46
6  
How did he describe them? Telling us what you currently understand will show you put some effort into this question and didn't just give us your homework assignment. Is Google down? – JeffO Mar 21 '12 at 13:06
Basically he had 2 projects open, the first one he called "driver" and the second one with all the constructors and the get/set methods. when he ran the program, driver was pulling data from the second project. but when he explains it that is when i could not understand. – Programmerwannabe Mar 21 '12 at 23:15
3  
You couldn't understand, so you didn't bother to write down what he said? Please tell me you were hung-over or you stayed up all night having sex-it is college afterall. – JeffO Mar 21 '12 at 23:59
If your professor is having trouble explaining something as basic as this in terms you can understand, I'm not sure how worthy he is of any respect at all... – Matt Mar 22 '12 at 20:35
show 1 more comment

6 Answers

Constructor

Used to initialize an object of the class and any members. Called only once for the lifetime of the object being initialized:

public class Person
{
   // Member.
   private String _name;

   // Constructor.
   public Person(String name)
   {
      _name = name;
   }
}

Example usage:

// Initialize object of Person class by calling constructor.
Person person = new Person("John Smith");

Get/Set Methods

Used to get or set values of object members respectively. Unlike constructors, set methods can be used to initialize member values more than once:

public class Person
{
    // Member.
    private String _name;

    // Get member value.
    public String getName()
    {
       return _name;
    }

    // Set member value to given value.
    public void setName(String name)
    {
       _name = name;
    }
}

Example usage:

// Initialize object of Person class.
Person person = new Person("John Smith");

// Get name of this person.
String name = person.getName();

// Set new name for this person.
person.setName("John Doe");
share|improve this answer
3  
Tip: NEVER change anything with a get function! – Jeffrey Sweeney Mar 21 '12 at 2:47
1  
@JeffreySweeney, How about lazy loading techniques? – Michael Kjörling Mar 21 '12 at 13:53
1  
@MichaelKjörling ...maybe, assuming that something's initialization status doesn't affect anything (and it often does unintentionally). – Jeffrey Sweeney Mar 21 '12 at 13:56
3  
putting an _ in front of variable names is a terrible practice in pretty much every language ( except Erlang where it means something specific semantically ) you should reference instance variables with this.name instead! – Jarrod Roberson Mar 22 '12 at 15:13
4  
Consistently terrible practices are still terrible practices, but made into rigid religious and dogmatic tautologies. They should not be taught to people just starting out, especially not in 2012 where the original reason for this practice was because of lack of quality tools for editing code, which has not been a concern for more than 10 years! – Jarrod Roberson Mar 22 '12 at 15:31
show 2 more comments

Plainly and simply:

  • Constructor: A special "function" within a class that is called every time an object is created (i.e. when you use new). Generally used to initialize the member variables.
  • Getter/Setter: "Functions" (or more correctly: methods) used for manipulating member variables, generally after the object is created from the class. They are just called that because, by convention, their names begin with get (for the methods that return the value of a given member variable) and set (for the methods that allow you to change the value).

These concepts are valid in any object oriented language, not just Java.

share|improve this answer

Class constructors are called just once, when the class is instantiated into a live object. Constructors are typically used to force the new, live object into a known state before anything else can act on it.

For example, if you have a Ball class with a size member variable whenever a new Ball is created the constructor should ensure that size is initialized to some safe value and not some random number. Alternately your Ball constructor can require someone making a new Ball to specify how big a size they want.

Get/Set methods are great for protecting live objects from just anyone poking around and making stupid or dangerous changes. They are also great for allowing your class to do extra work required when some property is change.

For example, your Ball has a setSize(int newSize) so someone can pump it up bigger. This set() function can make sure newSize is a safe value and also do extra work required inside your class like adjust a hidden airPressure member variable used in the hidden ball physics simulation that a user of the class shouldn't have to worry about.

Another example, your Ball has a getMaterialRequired() that returns how much rubber is needed to make a Ball based on what its size is. Someone outside should not know how the Ball knows how much rubber is required, all they need is to know how much. So the get() function both hides the complexity and can do extra work to create results whenever needed.

share|improve this answer
+1 for demonstrating that getters/setters can do extra work and that they're designed to protect data access. – Eric Hydrick Mar 22 '12 at 18:50

A constructor initializes an object. In other words, when you call the constructor method (function), it sets the instance attributes of the class to what is passed in as the parameters to the constructor as the initial state of the object.

Here's a way to think about it. A class is an idea. An object is the actual thing that the class describes. An analogy would be that the difference between an object and a class is much like the difference between a tree (a physical object with leave and roots and branches) and the idea of a tree (a mix of remembered physical sensations and words that exist in the mind).

In simplest terms, the constructor turns the idea into a thing. The constructor is a static member of the class, which means it belongs to the class (the idea) not the object (the thing) represented by the class.

Now, getters and setters are a completely different topic. To understand them, I would recommend that you review the "public", "private", and "protected" keywords. Any explanation of what getter and setter methods do will make no sense until you understand what these keywords do and why they are in the language. (Hint: The typical use case for Java in the real world is on projects that involve multiple programmers building software in teams. Private and protected members serve to hide complexity from developers who are using classes that have already been compiled and, ideally, documented. When object oriented programming is done well, the resulting classes and objects should have a single, logical pattern of use that can be understood without knowing the details of the implementation.) Once you understand all that, the following will make sense.

A getter is a method that provides read access to a private or protected property (variable).

A setter is a method that provides write access to private or protected property. A setter may include some data filtering capability.

Putting a getter on a class without a setter effectively makes a private or protected property read only to users of the class.

share|improve this answer

I just wanted to help give an example of how getters/setters might look in some practice

You (presumably) have some sort of credit card. You can adjust your available balance by making new charges or paying money back. You need to see your balance, but you shouldn't be able to just set it to whatever you feel like. We solve this problem by not letting you access your balance directly, but rather through a (i.e. getBalance()). You may want to know how much money you can still charge. The credit card company can also use a getter method to return calculated data. For example, checking your available balance (getAvailableBalance()) could read something like return getTotalCredit() - getBalance();.

Now, you're in college, which isn't permanent. At some point, you'll graduate and move. You need to change your address information with the credit card company. You can't just set your address to anything you want ("Send my bills to this address that corresponds to absolutely nowhere."). You need to update that value, so the credit card company writes some code to update that address. So you have things like setAddress(newAddress). That method may look something like:

if (isRealAddress(newAddress)) {
    address = newAddress;
} else {
    showErrorMessage("You entered an invalid address. Please correct it and try again.");
}

This makes sure that every time you try to change your address, it's to the real thing. You can also use methods to change values without just overwriting them. For instance, with a credit card, you could have methods like:

public String charge(amount) {
    // Can't let you go over your credit limit!
    if (balance + amount > totalCredit) {
        return "DENIED";
    } else {
        balance += amount;
        return "APPROVED";
    }
}
public void pay(amount) {
    balance -= amount;
}

These don't "replace" the old value of a variable like in most setter methods, but they do update the value with checks as needed (like not letting you exceed a credit limit).

share|improve this answer

A constructor creates the space in memory that will store your object that you are creating. That would be what a constructor with no arguments does.

Foo f = new Foo();

The constructor can also be written to take arguments, and execute code that will be executed when you create the object. This so you can ensure that the object is in a specific state after it is created, but before it is used.

Foo f = new Foo(1,"abc");

Get and set methods simply wrap members

private Foo _foo;
public Foo Get() { return _foo; }
public void Set(Foo f) { _foo = f; }

This is so you can hide internal state, or do verification before some value is retained. For example a property of type int may need to be between the values of 1 and 10. In your setter you could verify that the value is indeed between 1 and 10, and then take appropriate action if it is not.

private int _volume;
public int GetVolume() { return _volume; }
public void SetVolume(int volume) {
   if (volume < 1 || volume > 10) {
     // take appropriate action
   } else {
     _volume = volume;
}

In summary, they both exist to allow you better control over what a class can and cannot do. Here is a full class that uses both.

class VolumeController {
  public VolumeController(int min, int max) {
    // these don't ever change so set them up in the
    // constructor so once the object is created
    // we always have a valid min and max value
    // for the volume
    _min = min;
    _max = max;
    // default to _min so it is always
    // has a valid value
    _volume = min;
  }

  int _min;
  int _max;


  int _volume;

  public int GetVolume() {
     return _volume;
  }

  public void SetVolume(int value) {
    // here we need to ensure that the volume never
    // gets put in an invalid state
    if (value < min) {
      value = 0;
    } else if (value > max) {
      value = max;
    }
    _volume = value;
  }
}

You should be able to see from the example what a constructor is for, it creates the object and puts it in a valid initial state. The property getter and setter methods allow you to control how a value is set. This class makes it very easy for someone to use your volume controller in an application without worrying if it will throw an exception and break their code. This is the point of both constructors and property setters and getters.

share|improve this answer
1  
why the downvote? – Charles Lambert Mar 22 '12 at 15:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.