-
String to an object?
Hello, I am very new to Java so please forgive me!
I am doing some tutorials on associating classes. I have 2 classes; 1 called User, the other called Email. A 'user' has an 'email' address.
I need to do a setEmail method in the User class, but I am having a problem. Here is a bit of my code...
My User class...
public abstract class User {
private Email email;
private String name;
private String userId;
public User() {
name = "";
userId = "";
email = null;
}
public void setEmail(String email) {
this.email = email;
}
My Email class:
public class Email {
private String email;
public Email() {
email = "";
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
In setEmail (in the User class) I want to use the string parameter to create a new 'Email' object and place it in the email variable. How can I do this?
I am getting an incompatible types error... because the Email is an object and the email variable is a string?
Please any help is much appreciated,
thankyou! :o
-
You have to make a new Email object and set it's (String) email member; something like this:
Code:
public void setEmail(String email) {
Email e= new Email(); // create a new Email object;
e.setEmail(email); // set its email address
this.email= e; // set the Email object in this class
}
imho you should also create another c'tor in your Email class, one that takes a String argument.
kind regards,
Jos
-
Hello,
JosAH is Right...
You might could also decide to Change the parameter the setEmail() takes to Email, That's why it's giving you an incompatible type.
All the best!!!
-
Thankyou!!
Thankyou very much for your quick replies!!
I am just starting with Java and you've helped me alot,
thankyou again! :D :D