在Java中的类的主体内实例化对象 [英] Instantiating object from inside the main of that class in Java
问题描述
我通过我的OOP类文档,我发现这个例子:
I was looking through my OOP class documentation and I found this example:
class Student {
private String name;
public int averageGrade;
public Student(String n, int avg) {
name = n;
averageGrade = avg;
}
public static void main(String[] args) {
Student s = new Student("John", 9);
}
}
我觉得很困惑,主要是同一个类。这被认为是不好的做法吗?新创建的对象 s
有主方法吗?
谢谢!
推荐答案
这里没有什么错。这是完全正常的。 (不可否认,对于具有main方法的类来说,显然可以执行更有意义 - main
$ c> Student 类不太有意义。)
There's nothing wrong at all with this. It's entirely normal. (Admittedly it would make more sense for a class with a main method to be something one could obviously execute - a main
method in a Student
class doesn't make as much sense.)
对象实际上没有方法 - classes 有方法,无需任何特定上下文调用的静态方法,以及在该类型(或子类)的特定对象上调用的实例方法。
Objects don't really have methods - classes have methods, either static methods which are called without any particular context, and instance methods which are called on a particular object of that type (or a subclass).
虽然您可以调用 s.main(...)
,但实际上只是解析为静态方法的调用 Student.main
;你不应该调用静态方法via这样的表达式,因为它很混乱。
While you could call s.main(...)
that would actually just resolve to a call to the static method Student.main
; you shouldn't call static methods "via" expressions like this, as it's confusing.
这篇关于在Java中的类的主体内实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!