public class Cat {
//What happened to this variable?
private String name = "nameless cat";
public void setName(String name) {
//write your code here
this.name = name;
}
public static void main(String[] args) {
Cat cat = new Cat();
cat.setName("Simba");
System.out.println(cat.name);
}
}
What happened to String Name Variable
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Nouser
17 January 2021, 18:34
You assigned a new name (Simba) using the constructor with a string parameter. If there should be the possiblility to either set the name and keep the default value, then you should add a default constructor and call that (for the default name).
0
Dinesh
18 January 2021, 06:11
Is there any possibility as such?
0
Nouser
18 January 2021, 07:12
uhm, I do not fully understand? You can have default values for your fields but you must not. You can initialize them when instantiating them but you must not. You can have different constructors for different use cases but you must not. You even can sanitize and change data sent to the constructor to instantiate objects. And you can change fields later either directly (in some use cases not that a good idea) or through methods. You can have factory methods for an easy creation of objects and you can come up with own ideas to do so.
0