Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating object from inside the main of that class in Java

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);
    }
}

I find it confusing that they are instantiating an object from the main of the same class. Is this considered bad practice? Will the newly created object s have a main method?

Thank you!

like image 857
Mihai Neacsu Avatar asked Oct 25 '11 16:10

Mihai Neacsu


People also ask

Can you instantiate an object within the class?

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor.

How do you instantiate a main class in Java?

Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.


1 Answers

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.

like image 99
Jon Skeet Avatar answered Sep 22 '22 01:09

Jon Skeet