Reputation: 249
public class HelloWorldV3
{
//default constructor
HelloWorldV3()
{
}
//print two lines of text
public void printTwoLines( )
{
System.out.println("Hello, Virtual World!");
System.out.println("It is a great day for programming.");
}
//main method
public static void main(String [] args)
{
HelloWorldV3 hello = new HelloWorldV3( );
hello.printTwoLines();
}
Hi, I am beginning to learn about constructors, and I am having trouble understanding some code. In the program above, I know that a constructor was created, but it is empty. The printTwoLines() function prints the two lines, and the main method uses the constructor to call the function. I had questions about why there needs to be the "HelloWorldV3 hello = new HelloWorldV3();" line, and what would happen if there was actually something in the constructor.
Upvotes: 0
Views: 495
Reputation: 467
The:
HelloWorldV3 hello=new HelloWorldV3();
line makes a variable called hello. Hello is a different type of variable than what you are probably used to, and doesn't store a number, or integer, or anything like that, but an object (really the location of the object, but don't worry about that for now). You could also write it as :
HelloWorldV3 hello;
hello=new HelloWorldV3();
just as you would write:
int i;
i=5;
You can then access either the hello variable or the i variable.
As for the second part of your question, anything in the constructor would be called when the code:
new HelloWorldV3();
is executed. So you could put some code inside the constuctor like this:
public HelloWorldV3() {
System.out.println("In the constuctor");
}
Upvotes: 1
Reputation: 4445
You need the line
HelloWorldV3 hello = new HelloWorldV3( );
because that is what creates an instance (object) of the class HelloWorldV3
, allowing you to call its methods and access its fields (if any).
Java does some things behind the scenes to instantiate an object, and the concept of a constructor exists to allow you to specify code to execute (mostly initialization stuff) when Java is creating an instance of the class.
If there was code in the constructor, that code would execute when the line
HelloWorldV3 hello = new HelloWorldV3( );
executes.
To answer your question with a question, if there wasn't that line, then how would you ever call the printTwoLines()
method?
Upvotes: 0
Reputation: 370
The constructor will initilize your object "hello" of type "HelloWorldV3". If there is a code in the constructor, it will be executed when calling "new HelloWorldV3( )" in your first line of code of the method. So it will be executed before the method "printTwoLines". I hope I was clear :) Thanks.
Upvotes: 0
Reputation: 37023
It's just that you allocating the space with new operator for your HelloWorldV3 object.
It's always good to define state in constructor. By state i mean is, if you have say int field, you could initialize it to say default value that might be appropriate when you create your object (say to value 10)
Upvotes: 0