The user1 object from your signup class and your sendmail class are different. Surely their variable is named the same way but they refer to different Objects. To access the password from the user you have to pass the user to the sendmail class e.g.:

Signup.java

public class signup
{

  public void settingPassowrd()
  {
    users user1 = new users();
    user1.setapassword( "player" );

    sendmail mail1 = new sendmail();
    mail1.Sendsmail(user1);

  }
}

with:

public class sendmail
{

  public void Sendsmail(user usr)
  {

    usr.getpassword(); // getting password

    System.out.println( usr.getpassword() ); // will be the proper value from now on.
  }
}
Answer from L.Spillner on Stack Overflow
๐ŸŒ
Codefinity
codefinity.com โ€บ courses โ€บ v2 โ€บ 0bfa1111-8677-478f-bcd3-315dff1d7d40 โ€บ fe9d9ca0-ad3b-4c2b-abd4-7880cf383e83 โ€บ fbe43ee7-43e0-4188-b101-71e3ec5e9953
Learn Getter and Setter | Classes Advanced
All Java programmers use constructs called getters and setters. Getters and setters are methods that follow a specific pattern. They are used to bypass the private access modifier and effectively manipulate fields from another class.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_encapsulation.asp
Java Encapsulation and Getters and Setters
public class Person { private String ... public void setName(String newName) { this.name = newName; } } The get method returns the value of the variable name....
Top answer
1 of 3
2

The user1 object from your signup class and your sendmail class are different. Surely their variable is named the same way but they refer to different Objects. To access the password from the user you have to pass the user to the sendmail class e.g.:

Signup.java

public class signup
{

  public void settingPassowrd()
  {
    users user1 = new users();
    user1.setapassword( "player" );

    sendmail mail1 = new sendmail();
    mail1.Sendsmail(user1);

  }
}

with:

public class sendmail
{

  public void Sendsmail(user usr)
  {

    usr.getpassword(); // getting password

    System.out.println( usr.getpassword() ); // will be the proper value from now on.
  }
}
2 of 3
1

Please follow the standard coding conventions. I changed your code with standard coding conventions. just copy paste it , it will work

Users class

public class  Users {
private String password;
public users (){}
// GETTING PASSWORD
public String getpassword(){

    return password;
}
// SETTING PASSWORD
 public void setapassword(String password){
     this.password=password;
 }
}

Signup class

public class Signup {

public void settingPassowrd(){

    Users  user1 =new Users();
    user1.setapassword("player"); 

    SendMail mail1 =new SendMail(user1);
    mail1.Sendsmail();

}
}

SendMail class

public class SendMail   {
    private Users user1;
    SendMail(Users user1){
        this.user1 = user1
    }
    public void  sendMail(){
    user1.getpassword(); //getting password 
    System.out.println(user1.getpassword()); // If print here I get null
}
}

Main class to test the code

 public class SignupMain {

public static void main(String[] args) {

 Signup signup1= new Signup();
 signup1.settingPassowrd();
}

}
Top answer
1 of 6
10

Whenever you write this

GetterAndSetter gs = new GetterAndSetter();

what you're doing is to create a new instance of GetterAndSetter. Two instances that you create won't have any connection between them.

Inside class A, you create a new instance, and set its value. Inside class C, you create a new instance, and read its value. But because you've got two different instances, the value you're reading isn't connected with the value you're setting.

This is roughly like:

  1. I buy an envelope, and put some money inside it.
  2. Later on, I want to get the money back, so I buy a new envelope, and look for the money inside it.

You have to be looking in the same envelope that you put the money in, if you want to find it!

2 of 6
4

In class A, your code creates a new instance of GetterAndSetter and sets a value to the property. In class B, however, your code creates again another new instance of GetterAndSetter , then gets the value.

The instances your code works with in classes A and B are not the same - hence you don't obtain the values set in A when trying to get it in B. The instance of GetterAndSetter created in B is not used anymore after the code in B exits.

To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B. You can do this e.g. by passing it as a parameter to a method of B, or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter.

An example of the first option (pass as parameter):

Class A{
...
 GetterAndSetter createAndSet();
    int a = 10;
    GetterAndSetter gs = new GetterAndSetter();
    gs.setValue(a);
    return gs;
  }
...
}

class B {
...
 void getValueFromGetterAndSetter(GetterAndSetter gs) {
    int c;
    c = gs.getValue();
    ...
 }
...
}

To connect the instances, we of course also need to have another piece of code (assuming instances of A and B exist already):

...
        b.getValueFromGetterAndSetter(a.createAndSet());
...
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ methods in java โ€บ getters and setters
Getters and Setters Methods in Java
July 23, 2024 - Cat's name: Smudge Cat's age: 5 Cat's weight: 4Now another class (Main) can access the Cat fields, but only through getters. Note that getters have the public access modifier, i.e. they are available from anywhere in the program. But what about assigning values? This is what setter methods are for
๐ŸŒ
Quora
quora.com โ€บ How-can-I-do-getter-and-setter-method-of-instance-of-another-calss
How to do getter and setter method of instance of another calss - Quora
Answer: I'm a little confused. If you have a class people with an array of friends - are you asking how to create a getter and setter within the Friend class? In that case, don't worry about the People class. Just worry about the Friend class. In that case you would add getters to the definit...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 36586900 โ€บ calling-a-method-from-another-class-with-setters-and-getters-in-java
Calling a method from another class with setters and getters in Java - Stack Overflow
We're supposed to be working with setters and getters on this assignment, and they asked to create a variable for private double score; then create setters and getters to hold the score, but then a method to say whether the grade is an a, b, c, d or f after the user enters his score.
Find elsewhere
๐ŸŒ
DZone
dzone.com โ€บ data engineering โ€บ data โ€บ java getter and setter: basics, common mistakes, and best practices
Best Practices for Java Getter and Setter - DZone
October 1, 2019 - For the setter, add cloned items from the source Collection to the destination one. For the getter, create a new Collection, which is being returned. Add cloned items from the original Collection to the new one.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 639635 โ€บ java โ€บ access-getter-method-class
How to access a getter method from a different class? (Beginning Java forum at Coderanch)
September 16, 2014 - If, somewhere else in your code, you are creating an instance of A and initialising it with values from a properties file, then that is a different instance of A from the one you are creating in B. If you want to use the original A instance in your B instance then you need to pass it to the B instance - maybe as an argument to the constructor or to a setter method. ... Russy Bond wrote:Sorry about not adding more details. Actually I am using a @BeforeClass annotation of TestNG which makes sure myTestMethod gets definitely invoked and the name variable also gets set. I am able to print the value in TestA class. My only problem is now how to print this name or make the getter name print the value in TestB class.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ java-getters-and-setters
Getters and Setters in Java Explained
January 25, 2020 - By convention, getters start with the word "get" and setters with the word "set", followed by a variable name. In both cases the first letter of the variable's name is capitalized: public class Vehicle { private String color; // Getter public ...
๐ŸŒ
CodeJava
codejava.net โ€บ coding โ€บ java-getter-and-setter-tutorial-from-basics-to-best-practices
Java Getter and Setter Tutorial - from Basics to Best Practices
September 30, 2019 - For the setter, add cloned items from source collection to the destination one. For the getter, create a new collection which is being returned. Add cloned items from the original collection to the new one. If you define a custom type of object, you should implement clone() method for your own type.
Top answer
1 of 11
42

You CAN do either one. However, your professor might appreciate using the methods instead of the direct access. Here's why.

Let's say you have a class like this:

class SomeClass {
    private int someValue;
    private String someString;

    public SomeClass(int someValue, String someString) {
        this.someValue = someValue;
        this.someString = someString;
    }

    public int someValue() {
        return this.someValue;
    }

    public String someString() {
        return this.someString;
    }

    public String toString() {
        return someValue + ": " + someString;
    }

}

It's pretty straightforward, right? Well, what if all of a sudden we want to CHANGE the implementation of how we calculate someValue, and base it off of someString:

public int someValue() {
    int value = 0;
    for(int i = 0; i < someString.length; i++) {
         if(someString.charAt(i) == ' ') value++;
    }
    return value;
}

Now you also have to change every place where variable someValue was used.

So if you want to make the code easier to maintain in the long run, use the methods calls. This way when you code changes on you (and trust me, it changes all the time) you only have to change it in one spot instead of two.

And yes, you would want to use a method call in getting someString instead of the direct access in the last method :-)

2 of 11
22

When I design a class I try to make a clear distinction between the inside (implementation details) and the outside (the interface exposed to the world). Getters and setters provide a convenient place to convert values between the form in which they are stored in the objectโ€™s instance members and the form in which the outside world sees them. Using getters and setters internally would muck that up, because they'd be getting used by both the inside and outside.

If you find yourself wanting to hide part of a class from another part of the same class, consider breaking off the part you want to hide into its own class.

๐ŸŒ
Medium
medium.com โ€บ javarevisited โ€บ what-are-getters-and-setters-in-java-and-why-use-them-9fc7a72dae29
What are Getters and Setters in Java and Why Use Them? | by Firas Ahmed | Javarevisited | Medium
March 25, 2024 - By convention, the getters start with โ€˜getโ€™ while setters start with โ€˜setโ€™ followed by the variable name. ... public class AnotherClass { public static void main(String[] args) { Example example = new Example(); //getter String name = example.getName(); System.out.println(name)โ€ฆ ... Hey, I'm a backend developer and I love to share what I learn with the community. ... A humble place to learn Java and Programming better.
Top answer
1 of 1
6
Sarah; This is a great question. getters and setters come out of one of the fundamental Object Oriented Programming (OOP) concepts called encapsulation. Encapsulation is a way of wrapping data (variables) and the coding doing something with that data (methods) together. We encapsulate class variables and hide them from other classes and make them accessible only through methods of the current class. To achieve encapsulation in Java Declare the variables of a class as private. Provide public setter and getter methods to modify and view the variables values. That sounds all great and, if you are anything like me, doesn't really mean much without an example. So, let's do that. ```Employee.java public class Employee{ private String name; private String idNum; private int age; public int getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; } public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; } public void setIdNum( String newId){ idNum = newId; } } ``` Obviously we would store much more about an employee, but this is just a sample. Now, to your question of how do you access this "hidden" data from another class. ```RunEmployee.java public class RunEmployee{ public static void main(String args[]){ Employee employee = new Employee(); employee.setName("James"); employee.setAge(20); employee.setIdNum("12343ms"); System.out.print("Name: " + employee.getName() + " | Age: " + employee.getAge() + " | Id: " + employee.getIdNum()); } } ``` If we were to run this, assuming I don't have any syntax errors, we would get the following output: java Name: James | Age: 20 | Id: 12343ms Some of the benefits of encapsulation include: The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code. Post back if you have further questions. Happy coding, Ken
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ significance of getters and setters in java
Significance of Getters and Setters in Java | Baeldung
January 16, 2024 - A setter updates the value of a variable, while a getter reads the value of a variable. In this tutorial, weโ€™ll discuss the problems of not using getters/setters, their significance, and common mistakes to avoid while implementing them in Java.
๐ŸŒ
xperti
xperti.io โ€บ home โ€บ java getters and setters: basics, common mistakes, and best practices
Getters And Setters In Java: Common Mistakes, And How To Avoid Them?
April 28, 2022 - If their values are reset using a getter method or a reference method, it transforms into a big maintainability issue which is very difficult to debug. The best practice is to always use defensive copy (deep cloning) when making getters and setters in java for mutable data types. The java.util.Date class implements the clone() method from the Object class.
๐ŸŒ
Intellipaat
intellipaat.com โ€บ home โ€บ blog โ€บ getters and setters in java
Getters and Setters in Java - Explained with Examples
August 13, 2026 - Only add getters and setters for the fields that require external access or modification. Add the Getters and Setters in the fields that have to be accessed or changed from outside of the class.