Instantiating object from inside the main of that class in Java

前端 未结 5 978
萌比男神i
萌比男神i 2020-12-08 15:58

I was looking through my OOP class documentation and I found this example:

class Student {
    private String name;
    public int averageGrade;


    public         


        
5条回答
  •  悲&欢浪女
    2020-12-08 16:34

    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.)

    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).

    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.

提交回复
热议问题