英文:
Parametric constructor, what is the difference?
问题
Example A:
public class Dog {
private String dogName;
public Dog() {
dogName = "Toby";
}
public String getDogName() {
return dogName;
}
public static void main(String args[]) {
Dog object = new Dog();
System.out.println(object.getDogName());
}
}
Example B:
public class Dog {
private String dogName;
public Dog(String dogName) {
this.dogName = dogName;
}
public static void main(String args[]) {
Dog object = new Dog();
System.out.println(object.getDogName());
}
public static void main(String[] args) {
Dog object = new Dog("Toby");
System.out.println(object.dogName);
}
}
(Note: I've corrected the class name to start with a capital letter, which is the standard naming convention for classes in Java.)
英文:
I'm currently reviewing the in general (two) ways to make constructors, both default and parameterized, and I wanted to question what is the difference between these two examples.
Example A:
public class dog {
private String dogName;
public dog() {
dogName = "Toby";
}
public String getDogName() {
return dogName;
}
public static void main(String args[]) {
Dog object = new Dog();
System.out.println(object.getDogName());
}
}
Example B:
public class dog {
private String dogName;
public dog (String dogName) {
this.dogName = dogName;
}
public static void main(String args[]) {
Dog object = new Dog();
System.out.println(object.getDogName());
}
public static void main (String[] args) {
Dog object = new Dog("Toby");
System.out.println(object.dogName);
}
}
答案1
得分: 1
Example A:
public Dog() {
dogName = "Toby";
}
You are hardcoding "Toby" here. So, each time you will instantiate the object of type *Dog*, `dogName` will be initialized to "Toby", as a *default* value, because you have no option to pass the data dynamically during object instantiation with `new` keyword.
---
Example B:
public Dog(String dogName) {
this.dogName = dogName;
}
You are dynamically passing the value each time you create the object of type *Dog*. Each time you do so, `dogName` will be initialized to whatever you pass in, as an argument, into constructor.
英文:
Example A:
public Dog() {
dogName = "Toby";
}
You are hardcoding "Toby" here. So, each time you will instantiate the object of type Dog, dogName
will be initialized to "Toby", as a default value, because you have no option to pass the data dynamically during object instantiation with new
keyword.
Example B:
public Dog(String dogName) {
this.dogName = dogName;
}
You are dynamically passing the value each time you create the object of type Dog. Each time you do so, dogName
will be initialized to whatever you pass in, as an argument, into constructor.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论