www.tutorialspoint.com Forum Index
Register FAQMemberlistUsergroupsTutorials PointLog in
Reply to topic Page 1 of 1
error in the Constructor section of the Java-methods tutori
Author Message
Reply with quote
Post error in the Constructor section of the Java-methods tutori 
I have found an error in the Constructor section of the Java-methods tutorial

"Most often you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method:just declare them inside the parentheses after the constructor's name.
Example:

Here is a simple example that uses a constructor:

// A simple constructor.
class MyClass {
int x;

// Following is the constructor
MyClass(int i ) {
x = 10;
}
}

You would call constructor to initialize objects as follows:

class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}

This would produce following result:

10 20"

This is not correct. The printout would be "10 10"

To get the intended printout the constructor needs to be:

MyClass(int i ) {
x = i;
}

I am new to Java and this section confused me until I tested it so it would be good to change it for future newbies.

View user's profile Send private message
Reply with quote
Post  
Thanks for pointing this out. I have fixed it.


_________________
Moderator, TP
Keep visiting and share this site with your friends.
View user's profile Send private message Send e-mail
Display posts from previous:
Reply to topic Page 1 of 1
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum