构造函数和方法之间的区别
Bellow是我在 Tutorials Points 上找到的一个例子,一个构造函数的例子。我得到了其中的大部分,但我只是不明白为什么你需要一个构造函数和一个方法。
public Puppy(String name){
System.out.println("Passed Name is :" + name );
}
我的问题是,是什么阻止你这样做?
public static void Puppy(String name){
System.out.println("Passed Name is: "+name);
}
这两个人一旦被调用,难道不是做同样的事情吗?
以下是完整的程序供参考:
public class Puppy {
int puppyAge;
public Puppy(String name) {
System.out.println("Passed Name is :" + name);
}
public void setAge(int age) {
puppyAge = age;
}
public int getAge() {
System.out.println("Puppy's age is :" + puppyAge);
//what does this return do? since the puppyAge is already printed above.
return puppyAge;
}
public static void main(String []args){
Puppy myPuppy = new Puppy("tommy");
myPuppy.setAge(2);
myPuppy.getAge();
System.out.println("Variable Value :" + myPuppy.puppyAge);
}
}