Set and Get Methods in Java

Set and Get Methods in java?

Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.

For example, for a member variable:

Integer x;

You might have methods:

Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }

chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.

Using set and get methods in java

No, setters are not needed at all when implementing immutable classes/objects:

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.

Immutability means that the state of the object remains constant after object is fully created / constructed.

Similarly, getters are not always required, depending on the specific implementation of the object API.

Set & Get Methods

Simple go like:

System.out.println("Enter another price");
double newPrice = keyboard.nextDouble();
obj.setPrice(newPrice);

and print your obj before / after that call (and of course: @Overwrite toString() on that class to get meaningful output).

How to create get and set methods for parameters in a class?

public static void main(String[] args) {

String Name;
int Id;
String Address;
Boolean IsPack;

}

You can't create getters and setters for these, since they are not created in your class, but locally in your main method. What you want is:

public class MyClass{

String Name;
int Id;
String Address;
Boolean IsPack;

// getter for Name
public String getName(){
return this.Name;
}
// setter for Name
public void setName(String name){
this.Name = name;
}

public static void main(String[] args) {

}
}

For these you'll be able to create getters and setters.
It's (most likely) best to declare them private, though.
Also: following naming conventions could help other people easier read your code. Name (with capital N) is more suited as name of a class, while name (lowercase n) is the name of a variable.

Java: set and get methods for strings

The only problem I see is in the implementation of setName itself. You don't use the input variable thename at all.

public void setName(String thename){

this.name=name;
}

The last line should be

this.name = thename;

But this would not give you the error you say you got (that setName doesn't exist). I'm guessing you either defined the actual method with all lowercase (like public void setname(String thename)) or we are not seeing all of the code.



Related Topics



Leave a reply



Submit