Reputation: 2095
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!
Upvotes: 20
Views: 40625
Reputation: 1526
It's totally fineIt's totally fine... If a member of a class is declared as static,it's an entity lives differently of any particular object of the class.Its something that can be used by itself,without using any objects. OR it's common between different objects.You can actually count the number of objects created from a class,by setting up a static variable in the class like
class A
{
A()
{
count++
}
static count=0;
---
---
}
And each time an object of A,created count will add one.
Since static methods does not belong to any objects particularly,Outside the class,its called as
classname.method()
just like ordinary methods are called as classObject.method()
Upvotes: 1
Reputation: 59193
This is just fine.
I know it looks a bit recursive, but what happens is that the main() method gets called when you launch this class from the command line, and then the constructor gets called when you actually instantiate an instance of the object. (See Jon's comment as well.)
Upvotes: 4
Reputation: 115328
It is neither bad nor good.
It depends on the usage. In your example the constructor is called from main()
method that is static by definition, so you have no other choice.
Yet another example of "good" usage of this pattern is factory method pattern.
Enums use this technique too in valueOf()
method (that is an example of factory method too).
Upvotes: 2
Reputation: 691685
No, it's not bad practice. It's actually fairly frequent. What you missed is that main is a static method. It's not a method of the Student object. It's a method of the Student class. You don't invoke it with someStudent.main(...)
, but with Student.main(...)
.
See http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html for more explanations.
Upvotes: 16
Reputation: 1500105
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.
Upvotes: 19