构造函数和方法之间的差异 [英] Difference between constructors and methods
问题描述
Bellow是我在Tutorials Points上发现的一个例子,它是一个构造函数的例子。我得到了大多数,但我只是不知道为什么你需要一个构造函数和一个方法。
Bellow is an example I found on Tutorials Points, an example of a constructor. I got most of them, but I just don't get why you need a constructor and a method.
public Puppy(String name){
System.out.println("Passed Name is :" + name );
}
我的问题是,什么阻止你这样做?
My question is, what stops you from doing this instead?
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);
}
}
推荐答案
没有得到一个实例的基本概念,这是OOP的根本。如果你想要一个比喻,让我们谈谈汽车。
You did not get the basic concept of an instance, which is fundamental in OOP. If you want a metaphor, let's talk about cars.
我很确定你知道一辆汽车是什么;你知道它使你能够从一个地方移动到另一个地方,它有4个轮子等。这是一个概念,您在车库中的实际汽车是此概念的实例(< = class )。
I'm pretty sure you know what a car is; you know that it enables you to move from one place to another, that it has 4 wheels and so on. It is a concept, and the actual car you have in your garage is an instance of this concept (<=> class).
构造函数的目标是创建一个实例,而不是打印一些文本。没有构造函数,你永远不能调用你的类的非静态方法。你不能驾驶汽车的概念,你将需要先建造一辆汽车。
A constructor's goal is to create an instance, not to print some text. Without a constructor, you will never be able to call a non-static method of your class. You won't be able to drive the concept of a car, you will need to build a car first.
只需查看那些概念;你将无处没有它。
Just review those notions; you will get nowhere without it.
这篇关于构造函数和方法之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!