If the print method is not static, you can instantiate an object and call the print method on that object (as you have done).
If the print method was static instead i.e.
static void print(String p)
{
System.out.println(p);
}
Then you would have to use the class name to call the print method i.e. printer.print("hi"). You should know that static methods are class methods i.e. all objects of the class use the same method.
With static print, note that even if you did create an object and call print on the object (as you did), this would still work but your IDE would typically show a warning, advising you to use the class name instead of the instance.
Now suppose you defined the printer class inside Test i.e. nested classes
class Test
{
public static void main(String args[])
{
new Test().new printer().print("Hello World!");
}
class printer
{
void print(String p)
{
System.out.println(p);
}
}
}
Then you can see that to call the print method, you would first have to instantiate a Test class object (outer class), then instantiate a printer object using the Test object (inner class) and then call print on the printer object. Why? This is because the printer class is not static, hence, you need to create an instance of it. Alternatively, if you declare your print method static i.e.
class Test
{
public static void main(String args[])
{
printer.print("Hello World!");
}
static class printer//note: only nested classes can be static
{
static void print(String p)
{
System.out.println(p);
}
}
}
Then you can see that you can call print using the class name printer. The moral of the story is that each time you see the word static, expect all objects to share that method (or variable) and hence, when you call that method (or variable), be sure to use the class name directly.
Also, it is good to follow naming conventions- in other words, use the name Printer rather than printer for the class.